When I was studying patterns, I went through main patterns in the alphabetical order. Adapter pattern was in the beginning and Template Method – in the end. And when I came to the latter and read about it, I was confused. Thee solve the same task, implement the same GRASP principle (Protected Variations) – they are the same, but why are they called differently?
But when I studied them both in more details, it turned out, that there is a significant difference between them. Yes, they solve the same things, but do this differently. To see this, take a look at UML’s:
Client calls the doRoutine() method of the correspondent adapter. And this adapter calls the specific method of each Adaptee. Adaptee may be some concrete class or some specific API or anything like this.
TemplateMethod() simply calls operations, that are different from class to class. Derived classes implement these operations (operation1(), operation2()…) and, as a result, we get working class with the functionality we need.
You see, using adapter is more like implementing the interface, while using Template Method is about implementing the parts of algorithm differently. So Adapter is used when we need all modules/components to response to the same API. At the same time, we use Template Method when we have some general process, which differs in minor details, which we implement in the derived classes.
For example, we should use Adapter pattern for the DB abstraction layer and TemplateMethod pattern for the calculation of table’s volume (see “What is OOP post”, I showed this example there)
No related posts.
Related posts brought to you by Yet Another Related Posts Plugin.