Strategy meets Template

From CSSEMediaWiki
Revision as of 03:11, 25 November 2010 by WikiSysop (Talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Strategy pattern defines a family of algorithms. Template method pattern defines the skeleton of an algorithm in an operation, deferring some steps to subclasses. If we combine those two patterns we can create separate strategy for all algorithms that differ significantly but make a further refinement of each strategy by utilizing the template method on the strategy that could have variations based on steps of execution. This could prevent horizontal expansion of strategies while utilizing all the variation on the each algorithm.

The UML example demonstrating solutions to transportation:


Strategy-Template.PNG


In this diagram, TransprtSolutionDemo is the main class with a main() method. This class is coupled to the TransprtSolution interface. This interface is implemented by two abstract classes: TransportMethod1 and TransportMethod2. Both abstract classes are extended by two subclasses: TransprtImpl1 and TransprtImpl2, respectively. By comparing this diagram with the structural diagram of the Strategy pattern, it is clear that TransprtSolution can be identified as Strategy, TransportMethod1 and TransportMethod2 can be identified as ConcreteStrategy (together with their subclasses), and TransprtSolutionDemo can be identified as Context (client). The whole problem demonstrates solutions to transportation. But there are two solutions: these are implemented in TransportMethod1 (with TransprtImpl1) and in TransportMethod2 (with TransprtImpl2). TransprtSolutionDemo holds a reference to TransprtSolution and creates objects of both implementations. With a simple call of the method solve() of the TransprtSolution interface, the solution will be calculated by both algorithms (the method is implemented in both implementation classes). These solve() methods in TransportMethod1 and TransportMethod2 are implemented using the Template Method pattern.

Personal tools