Head First 策略模式
Posted wwwx
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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(); } }
以上是关于Head First 策略模式的主要内容,如果未能解决你的问题,请参考以下文章