views:

229

answers:

1

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.

+4  A: 

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.

workmad3
+1 for a good concise explanation, and for mentioning composition over inheritance
Enrico Campidoglio