Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template Method and Strategy design patterns

This is probably a newbie question since I'm new to design patterns but I was looking at the Template Method and Strategy DP's and they seem very similar. I can read the definitions, examine the UML's and check out code examples but to me it seem like the Strategy pattern is just using the Template Method pattern but you just happen to passing it into and object (i.e. composition).

And for that matter the Template Method seems like that is just basic OO inheritance.

Am I missing some key aspect to their differences? Am I missing something about the Template Method that makes it more that just basic inheritance?

Note: There is a previous post on this (672083) but its more on when to use it, which kind of helps me get it a bit more but I want valid my thoughts on the patterns themselves.

like image 934
Cody Avatar asked Jun 12 '09 20:06

Cody


Video Answer


2 Answers

It basically all comes down to semantics. The strategy pattern allows you to pass in a particular algorithm/procedure (the strategy) to another object and that will use it. The template method allows you to override particular aspects of an algorithm while still keeping certain aspects of it the same (keep the order the same, and have things that are always done at the start and end for example... the 'template') while inheritance is a way of modelling 'IS-A' relationships in data models.

Certainly, template methods are most easily implemented using inheritance (although you could just as easily use composition, especially once you have functors), and strategy patterns are frequently also template methods but where the syntax is similar the meanings are vastly different.

like image 150
workmad3 Avatar answered Sep 20 '22 17:09

workmad3


The Strategy design pattern
provides a way to exchange the algorithm of an object dynamically at run-time
(via object composition).

For example, calculating prices in an order processing system.
To calculate prices in different ways, different pricing algorithms can be supported so that which algorithm to use can be selected (injected) and exchanged dynamically at run-time.

The Template Method design pattern
provides a way to redefine some parts of the behavior of a class statically at compile-time
(via subclassing).

For example, designing reusable applications (frameworks).
The application implements the common (invariant) parts of the behavior so that users of the application can write subclasses to redefine the variant parts to suit their needs. But subclass writers should neither be able to change the invariant parts of the behavior nor the behavior's structure (the structure of invariant and variant parts).

like image 22
GFranke Avatar answered Sep 19 '22 17:09

GFranke