Saturday, March 9, 2013

Template Method and Adapter Pattern

Template Method -

- The template of the flow is provided by an abstract base class, and the implementation is done by derived or subclasses.
- Example if we write a parser, then we will provide the flow of parsing in the base class in the following way
parser {
parseFile(){
 load();
 parse();
close();
}
}

excelParser : Parser{
load () {//load excel}
parse(){//parseExcel}
close(){close excel}
}
pdfParser : Parser{
load () {//load pdf}
parse(){//parse pdf}
close(){close pdf}
}

Adapter-

- Provide an intermediate class which can help translating one interface into another compatible one.
- As a simplest example lets consider there is data from one stream in one format and our class expect it in another format. In this case we provide an intermediate class which can convert it into desired format, that intermediate class is adaptor class.

- We can understand it in the form of class adaptor as well, say there is class consultant and employee. Employee implements IEmployee interface but consultant doesn't. If we want to put consultant into a list of IEmployee then we will have to provide another class say ConsultantToEmployee which implements IEmployee and extends consultant.

By this we can have consultants also get saved in the list of IEmployee.

No comments:

Post a Comment