Head First 策略模式
一、算法接口类及实现
public interface FlyBehavior { public void fly(); } public interface QuackBehavior { public void quack(); }
public class FlyNoWay implements FlyBehavior{ public void fly() { System.out.println("I can't fly"); } } public class FlyWithWings implements FlyBehavior{ public void fly() { System.out.println("I'm flying"); } }
public class Quack implements QuackBehavior{ public void quack() { System.out.println("Quack"); } } public class Squeak implements QuackBehavior{ public void quack() { System.out.println("Squeak"); } } public class MuteQuack implements QuackBehavior { public void quack() { System.out.println("<< Silence >>"); } }
二、抽象类及具体实现类
public abstract class Duck { //为行为接口类型声明两个引用变量,所有的鸭子类都继承它们 FlyBehavior flyBehavior; QuackBehavior quackBehavior; public Duck(){ } public abstract void display(); //委托给行为类 public void performFly(){ flyBehavior.fly(); } public void performQuack(){ quackBehavior.quack(); } public void swim(){ System.out.println("All ducks float, even decoys!"); } //动态设定行为 public void setFlyBehavior(FlyBehavior fb){ flyBehavior = fb; } public void setQuackBehavior(QuackBehavior qb){ quackBehavior = qb; } }
public class MallardDuck extends Duck { public MallardDuck(){ //根据需求选择行为 quackBehavior = new Quack(); flyBehavior = new FlyWithWings(); } public void display() { System.out.println("I'm a real Mallard duck"); } }
三、测试类
public class MinDuckSimulator { public static void main(String[] args){ Duck mallard = new MallardDuck(); mallard.performQuack(); mallard.performFly(); } }
四、类图