Monday, August 14, 2006

Java Strategy Design Pattern

See comments for three different types of behaviors:

public abstract class Duck {
FlyBehavior flyBehavior;
QuackBehavior quackBehavior;
public Duck() {
}
public void setFlyBehavior (FlyBehavior fb) {
flyBehavior = fb;
}
public void setQuackBehavior(QuackBehavior qb) {
quackBehavior = qb;
}
/******************************************************
* May vary from duck to duck.
*****************************************************/
public void performFly() {
flyBehavior.fly();
}
public void performQuack() {
quackBehavior.quack();
}
/******************************************************
* Common to all ducks
*****************************************************/
public void swim() {
System.out.println("All ducks float, even decoys!");
}
/******************************************************
* Different for all ducks
*****************************************************/
abstract void display();
}

This is an implementation. See how it got three different types of behaviors.

/**
* 1. Provide fly and quack behaviors
* 2. Impliment display behavior
* 3. Inherit swim behavior
*/
public class RubberDuck extends Duck {

public RubberDuck() {
flyBehavior = new FlyNoWay();
quackBehavior = new Squeak();
}
public void display() {
System.out.println("I'm a rubber duckie");
}
}

0 Comments:

Post a Comment

<< Home