![]() |
|
|
Review of Strategy Pattern Design Pattern: Elements of Reusable Object-Oriented Software by E. Gamma, et al. (1995) Reviewed by Samuel Lee |
The Strategy pattern "define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it" (Gamma, 1995). As an example, there are many algorithms that exist today for breaking a stream of text into lines but hard-wiring all algorithms into the classes is not desirable because:
- If the line breaking code is included, the clients get more complex, bigger and harder to maintain.
- In more cases, it is not appropriate to use all of them.
- Difficult to add and vary algorithms when a line-breaking is an integral part of a client
Strategy pattern avoid these problems by defining classes that encapsulate different algorithms.
Strategy pattern is used when:
- Many related classes differ only in their behavior
- Different variations of algorithm is needed
- Avoiding the exposure of algorithm data structures.
- A class defines many behaviors, and these appear as multiple conditionals in its operations
The following is the Strategy pattern structure.
![]()
figure 1: Strategy pattern structure (Kremer, 2003)
The Strategy pattern consist of:
- Strategy - define a common interface to all supported algorithm
- ConcreteStrategy - implements the algorithm that is defined in the Strategy interface
- Context - maintains a reference to a Strategy object and define an interface for Strategy to access its data. It is also configured with a ConcreteStrategy object
The consequences of Strategy pattern:
Strategy pattern is used by ET++ and InterViews to encapsulate different line-breaking algorithm. Borland's ObjectWindows also uses strategies in dialogs boxes to validate data that the user enters and ObjectWindows uses Validator objects to encapsulate validation strategies.
- Families of related algorithms
- An alternative to subclassing
- Strategies eliminate conditional statements
- A choice of implementations
- Clients must be aware of different strategies
- Communication overhead between Strategy and Context
- Increased number of objects
I think Strategy pattern is an efficient mechanism to save continuously use of if / else statements or the switch statement. One of the main benefit is that when ever there is a new strategy, the programming code of strategy's containing class does not need to be changed. Another benefit is that strategies allows the strategy to be pay as you needed basis, unlike the switch/case where every switch/case target is hard-coded into the switch/case. Depends on the implementation, switch/case statements can be quite long which makes it hard to debug, but unlike switch/case statement, Strategy pattern provides a cleaner and simpler way of implementing the same conditions.
![]() |
back |
up |
forward |
|
| |
||||