Pattern Reminder: Strategy
Starting a new series to remember the good old gof design patterns. The STRATEGY Pattern will be my first entry.
Definition: "Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from the clients that use it." [Gamma]
Java Example: The client uses a capsuled family of algorithms. In this case we encapsulate a behaviour.

Client:
public abstract class Fighter {
FightingBehaviour fightingBehaviour;
public Fighter(){ };
public void fight(){fightingBehaviour.fight(); }
public void setFightingBehaviour(FightingBehaviour fb) {fightingBehaviour = fb;}
}
Client Implementations:
public class Boxer extends Fighter
{
public Boxer()
{
fightingBehaviour = new BoxingBehaviour();
}
}
Algorithm:
public interface FightingBehaviour {
public void fight();
}
Algorithm Implementation:
public class BoxingBehaviour implements FightingBehaviour {
public void fight() {
System.out.println("Raise fist!");
}
}
Test it:
Fighter fighter = new Boxer();
fighter.fight();
Thats basically it. It is now very easy to add new behaviours or fighters and change their algorithms.
0 TrackBacks
Listed below are links to blogs that reference this entry: Pattern Reminder: Strategy.
TrackBack URL for this entry: http://www.innoq.com/mt4/mt-tb.cgi/2463
Leave a comment