Applied Design Patterns with Java

Behavioral :: Strategy (315) {C ch 24}


Example - Java :: Patterns\Behavioral\Strategy

Pattern Concept: to define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it. The Strategy pattern consists of many related algorithms encapsulated in a driver class called Context. The client or the Context can select which algorithm to use.

Strategy and State appear to be similar. However, State allows all of the different states to be active at one time, and switching between them could occur often. Strategy only allows one algorithm to be active from the Context at one time, and in Strategy there is no notion of switching between algorithms.

The core facility in the Strategy pattern is to do the same thing different ways, and to easily select the most suitable way as needed. All of the strategies are contained in a single module, and a straigtforward interface allows choosing between them. Each Strategy must have the same interface, but they do NOT need to be members of the same class hierarchy.

Cooper's example uses a core set of data, and the strategies involve representing the data in a plotted graphic differently:


PlotStrategy is an abstract class at the base of the hierarchy, with BarPlotStrategy and LinePlotStrategy as the derived children. The Context class is the mechanism that contains the PlotStrategy reference, and also the strategies and the means of selecting one of them:

public abstract class PlotStrategy extends JxFrame {

...

public abstract void plot(float xp[], float yp[]);

...

}

public class Context {

private PlotStrategy plotStrategy;

...

public void setBarPlot() {

plotStrategy = new BarPlotStrategy();

}

public void setLinePlot() {

plotStrategy = new LinePlotStrategy();

}

public void plot() { plotStrategy.plot(); }

...

public void readData(String filename) { ... }

}

public class BarPlotStrategy extends PlotStrategy {

private BarPlotPanel bp;

public void plot() { ... }

...

}

public class LinePlotStrategy extends PlotStrategy {

private LinePlotPanel lp;

public void plot() { ... }

...

}

This core Strategy pattern is realized in the PlotPanel hierarchy, which is contained in the BarPlotStrategy and LinePlotStrategy instances. Here is the hierarchy:


Example - UML : StrategyPlot
Here is Cooper's Class Diagram for the application using this Strategy logic, followed by the Rose equivalent:





The example Java program is called 'StrategyPlot'.

The UML diagram is above, and the list of Java files is below:

Issues and consequences of the Strategy pattern include:

Catalog Behavioral Prev Next