Definition: The Strategy pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from the clients that use it.
Usage: Find a behavior that varies from one object to another. Typical non-pattern code will have several classes extending one class just to change one method. Put this method in an interface and create classes that implement the interface. Then include getter/setter methods for an object of that interface within the base class. The child classes will no longer be needed.
interface SpriteRenderer {
render()
}
class PlayerRenderer implements SpriteRenderer {
render() {
draw the player
}
}
class Sprite {
draw() {
renderer.render();
}
getRenderer() {return renderer;}
setRenderer(SpriteRenderer renderer) {this.renderer = renderer;}
SpriteRenderer renderer;
}
In general, I would refer to the class Sprite as the "Context" of the Strategy. It is the class that uses the Strategy. SpriteRenderer and classes implementing it are the actual Strategy classes. This nomenclature is nonstandard because it's really both Sprite and SpriteRenderer together that forms the pattern. Separating the classes into "Strategy Context" and "Strategy" just makes it easier to recognize which class is which by reading comments at the start of the code.
Copyright (C) 2008-2009 Steven Fletcher. All rights reserved.