Strategy pattern
From GPWiki
The wiki is now hosted by GameDev.NET at wiki.gamedev.net. All gpwiki.org content has been moved to the new server. However, the GPWiki forums are still active! Come say hello. The Strategy pattern shows how to supply a variant of an algorithm by wrapping it in a class.
[edit] Definition[edit] ProblemYou want to be able to change how an algorithm works after the class that uses the algorithm has been finalized. [edit] Context
[edit] Solution
[edit] Example UsageImagine that you are developing a roleplaying game where you want to move your characters around on the map. You are interested in supplying different algorithms for movement for different types of characters. For instance, a human character needs to avoid collision with trees etc. while a ghost character can move right through buildings and a wizard character can teleport himself.
class Unit { private MoveAlgorithm moveAlg; public Unit() { moveAlg = new AStar(); } public Unit( MoveAlgoritm ma ) { moveAlg = ma; } public setMoveAlgorithm( MoveAlgorithm ma ) { moveAlg = ma; } public moveTo( int toX, int toY ) { String moves = moveAlg.getMoves( currentPosX, currentPosY, toX, toY ); print( "Moving unit: " + moves ); } } interface MoveAlgorithm { String getMoves( int fromX, int fromY, int toX, int toY ); } class BirdFlight implements MoveAlgorithm { public String getMoves( int fromX, int fromY, int toX, int toY ) { return "Moving in birdflight to position (" + toX + "," + toY + ")"; } } class AStar implements MoveAlgorithm { public String getMoves( int fromX, int fromY, int toX, int toY ) { return "Moving according to the A* algorithm to position (" + toX + "," + toY + ")"; } } Test: Unit player = new Unit(); // A* movement algorithm is on by default player.moveTo( 50, 50 ); // The player is killed and is transformed into a ghost. print( "Player is killed!" ); // Therefore we apply the movement algorithm for the ghost character. player.setMovementAlgorithm( new BirdFlight() ); player.moveTo( 70, 70 ); Output: Moving unit: Moving according to the A* algorithm to position (50,50) Player is killed! Moving unit: Moving in birdflight to position (70,70) Using the strategy pattern can have many benefits and can vastly improve the flexibility of your classes.
[edit] Additional Information |





