Pattern Reminder: Strategy

| | Comments (0) | TrackBacks (0)

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.

strategy.jpg


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.

Categories

,

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

About this Entry

This page contains a single entry by Christian Albrecht published on November 7, 2006 12:06 PM.

JUG Cologne was the previous entry in this blog.

Pattern Reminder: Observer is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.

Powered by Movable Type 4.0