Suggested Pages

Saturday, November 16, 2013

Design Pattern: Template Method vs Strategy


In this post we will speak about the main differences between the Design Pattern Template Method and Strategy; we're going to compare the situations when it's recommended to use the former or the latter.
First step is the comparison shown in the following table:
TemplateStrategy
Design OrientationVerticallyHorizontally
Concreate MethodologyFillingOverriding
Time UsingRuntimeRuntime

Template is used when you are interested in specializing a portion of a new or existing algorithms/behaviours.
Strategy instead is used to replace a current strategy with another one.
Both Design Pattern are used to change a behaviour at runtime, but they work differently: Strategy encourages Replacement of behaviours while Template encourages the Filling portions of behaviours.

Even if a Strategy can be realized through the mechanism of subclassing, you are planning to override functionalities and not filling portion of behaviours.
You can notice that when you increase the hierarchy of your strategies, you are moving towards the same mechanism Template.

Another difference it's that Template is useful when in a complex existing domain you cannot modify legacy code easly, and a Strategy can be very risky. Instead use a Strategy in a new context may be a more clean and clear to start with. This is only a brief summary but in the next week I will post concreate examples.

No comments :

Post a Comment

Suggested Pages