3. Role
The Strategy pattern involves removing an algorithm from its host class and putting it in a
separate class.
There may be different algorithms (strategies) that are applicable for a given problem. If the
algorithms are all kept in the host, messy code with lots of conditional statements will result.
The Strategy pattern enables a client to choose which algorithm to use from a family of
algorithms and gives it a simple way to access it.
The algorithms can also be expressed independently of the data they are using.
4. Illustration
The strategy pattern lets the algorithms vary independently from clients that use them. For
example, while sorting has many (like binary sort, quicksort), the algorithm is independent of how
to objects/elements are compared. So the sorting algorithm can vary/change independent of
compare algorithm. There are situations when this would be a poor choice and another
algorithm, such as Mergesort, would perform better. Even the linear sorts, such as Shellsort, can
perform very well under certain conditions.
When studying sorting, one learns about the different conditions to consider and how to
optimize the choice of algorithms. This is a strategy that can be captured in the Strategy pattern.
5. Design
UML Class Diagram
Participants
The classes and/or objects participating in this pattern are :
IStrategy (SortStrategy)
declares an interface common to all supported algorithms.
Context uses
this interface to call the algorithm defined by a Strategy.
Strategy (QuickSort, ShellSort, MergeSort)
implements the algorithm using the IStrategy interface.
Context (SortedList)
is configured with a Strategy object
maintains a reference to a Strategy object
may define an interface that lets Strategy access its data.
<<Interface>>
IStrategy
+Algorithm()
StrategyB
+Algorithm()
StrategyA
+Algorithm()
Context
+ContextInterface()
7. Implementation
We are going to create a IStrategy interface defining a action and concrete Strategy classes
implementing the IStrategy interface. Context is a class which uses a IStrategy.
The Client will use Context and Strategy objects to demonstrate change in Context behavior
based on Strategy it deploys or uses.
Step 1: Create an IStrategy interface.
Step 2: Create concrete classes implementing the same interface.
OperationAdd.vb
OperationSubstract.vb
OperationMultiply.vb
OperationDivided.vb
Step 3: Create Context class.
Step 4: Use the Context to see change in behavior when it changes its Strategy.