The Strategy Pattern: Design Principles
The Strategy Pattern: Design Principles
Toni Sellars
Universitat de Girona
Design Principles
Identify the aspects of your application that vary and separate
them from what stays the same.
Context
Strategy
ContextInterface ( )
AlgorithmInterface ( )
Context manages
the data
structures that
a concrete
strategy
operates on.
ConcreteStrategyA
AlgorithmInterface ( )
ConcreteStrategyB
AlgorithmInterface ( )
ConcreteStrategyC
AlgorithmInterface ( )
}
}
class Context
{
Strategy strategy;
public Context( Strategy strategy )
{
this.strategy = strategy;
}
public void contextInterface()
{
strategy.algorithmInterface();
}
}
public class ClientTest
{
public static void Main( string[] args )
{
Context c = new Context( new ConcreteStrategyA() );
c.ContextInterface();
Context d = new Context( new ConcreteStrategyB() );
d.ContextInterface();
Context e = new Context( new ConcreteStrategyC() );
e.ContextInterface();
}
}
Example
Consider a simplified graphing program that can present data as a line graph or
a bar chart.
3 classes : the generic PlotStrategy
LinePlotStrategy
BarPlotStrategy
Each plot will appear in its own frame -- so PlotStrategy is derived from
JFrame
Context
PlotStrategy
LinePlotStrategy
BarPlotStrategy
}
Set the Pen color. Set the kind of plot, read the
data and then plot the data.
Class Diagram
PlotStrategy
PlotStrategy ( )
findBounds ( )
plot ()
setPenColor ()
setSize ( )
BarPlotStrategy
BarPlotPanel bp
BarPlotStrategy ( )
plot ( )
BarPlotPanel
paint ( )
LinePlotStrategy
LinePlotPanel lp
LinePlotStrategy ( )
plot ( )
LinePlotPanel
paint ( )
Context
Context ( )
plot ( )
readData ( )
setBarPlot ( )
setLinePlot ( )
setPenColor ( )
JGraphButton
JGraphButton ( )
Execute ( )
JBarButton
JBarButton ( )
Execute ( )
Summary
Strategy pattern allows selection of one of several algorithms
dynamically.
Algorithms may be related via an inheritance hierarchy or
unrelated [must implement the same interface]
Strategies dont hide everything -- client code is typically aware
that there are a number of strategies and has some criteria to
choose among them -- shifts the algorithm decision to the client.