The StrategyDesign Pattern
© Allan C. Milne
v15.2.6
The one constant in software development …
CHANGE.
Inflexibility of rendering.
• Consider what requires to be changed if we wish to render a map on a different display technology …– The existing TiledMap code must be changed by
replacing the implementation of the render() method.
• Always a bad idea to change our existing code base to allow for new requirements:– may compromise related implementation and/or
functionality;– results in multiple versions;– complicates future maintenance.
The strategy design pattern …
• … defines a family of algorithms.• … encapsulates each algorithm.• … makes algorithms interchangeable.• … allows the algorithm to vary
independently of the clients that use it.
• In our scenario the family of algorithms are the different implementations of the map rendering behaviour.
The strategy pattern UML.
MyClass
… … …algorithm
… … …DoIt()
<<interface>> AlgorithmFamily
Algorithm()
Class2
Algorithm()
Class1
Algorithm()
Designing render behaviour.
TiledMap
… … …mRenderer
… … …setRenderer (MapRenderer)render()
<<interface>> MapRenderer
render (TiledMap)
ConsoleRenderer
render (TiledMap)
AudioRenderer
render (TiledMap)
Applies design principles …
• Identify aspects of the application that vary and separate them from what stays the same.
• Design to an interface, not an implementation.
• Favour composition over inheritance.
So how does this work?
• We create a TiledMap object and the constructor …– … assigns a supplied MapRenderer object.
• Thus each TiledMap type object may have its own rendering behaviour instantiated outside the TiledMap object.
• The aim here is to maintain the maximum flexibility in the design.
The flexibility of the design.
• Dynamically change the implementation of a behaviour of an object.
• Amend the concrete implementation of a behaviour.
• Allows us to add new implementations of a behaviour.
• All without changing any of the TiledMap class.
Implementing rendering …interface MapRenderer
{void render (TiledMap
aMap);}
class ConsoleRenderer implements MapRenderer { public void render (TiledMap aMap) { System.out.println (… …); … … … aMap.get(x,y) … … … }
} // end ConsoleRenderer class.
… and in the map class …
class tiledMap{ private MapRenderer mRenderer;
… … …
public void setRenderer (MapRenderer aRenderer) { mRenderer = aRenderer; }
public void render () { mRenderer.render (this);}
} // end tiledMap class.
The objects when executed … TiledMap map; map = new TiledMap (…, new ConsoleRenderer() );
map
mRenderer
…
render()
…(TiledMap object)
Render(this)
(ConsoleRenderer object)
call TiledMap(…) constructor method
Now follow the code …
… … … map.render();
map.setRenderer(new JPanelRenderer());
… … … map.render(); … … …
Top Related