(一)策略模式

策略模式定义了算法族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化独立于使用算法的客户。

设计原则:1、找出应用中可能需要变化之处,把他们独立出来,不要和那些不需要变化的代码混在一起。(把变化的飞行行为、呱呱叫行为从不变的鸭子类中取出来)

      

     2、针对接口编程,而不是针对实现编程。(FlyBehavior、QuackBehavior)

        3、多用组合,少用继承。(有一个比是一个更好)

      

Talk is cheap,

Duck类:

public abstract class Duck {

    /*
    * 行为接口
    * */
    FlyBehavior flyBehavior;
    QuackBehavior quackBehavior;

    public Duck(){

    }
    public abstract void dispaly();


    /*
    * 设定鸭子的行为
    * */
    public void setFlyBehavior(FlyBehavior fb){
        flyBehavior = fb;
    }

    public void setQuackBehavior(QuackBehavior qb){
        quackBehavior = qb;
    }

    /*
    * 委托给行为类
    * */
    public void performFly(){
        flyBehavior.fly();
    }

    public void performQuack(){
        quackBehavior.quack();
    }

    public void swim(){
        System.out.println("All dusks float,even decoys");
    }

}

Fly接口、Quack接口:

/*
* 飞行接口
* */
public interface FlyBehavior {
    public void fly();
}

public interface QuackBehavior {
    public void quack();
}

实现:

/*
* 不会飞的鸭子的行为
* */
public class FlyNoWay implements FlyBehavior{
    @Override
    public void fly() {
        System.out.println("i cant fly!!");
    }
}

public class FlyRocketPowered implements FlyBehavior{
    @Override
    public void fly() {
        System.out.println("i'm flying with a rocket!");
    }
}

/*
*真会飞的鸭子的行为
* */
public class FlyWithWings implements FlyBehavior{
    @Override
    public void fly() {
        System.out.println("i'm flying !!");
    }
}
public class MuteQuack implements QuackBehavior{
    @Override
    public void quack() {
        System.out.println("<Since>");
    }
}

public class Quack implements QuackBehavior{
    @Override
    public void quack() {
        System.out.println("Quack");
    }
}

public class Squeak implements QuackBehavior{
    @Override
    public void quack() {
        System.out.println("Sqeak");
    }
}

子类:

public class MallardDuck extends Duck{
    public MallardDuck(){
        quackBehavior = new Quack();
        flyBehavior = new FlyWithWings();
    }

    @Override
    public void dispaly() {
        System.out.println("i'm a real Mallard duck!");
    }
}

public class ModelDuck extends Duck{
    public ModelDuck(){
        flyBehavior = new FlyNoWay();
        quackBehavior = new MuteQuack();
    }

    @Override
    public void dispaly() {
        System.out.println("i'm a model duck!");
    }

}

 

测试:

public class MiniDuckSimulator {
    public static void main(String[] args){
        Duck mallard = new MallardDuck();
        mallard.performFly();//调用MallardDuck继承的performFly()方法,进而委托给该对象的FlyBehaviour处理
        mallard.performQuack();

        Duck model1 = new ModelDuck();
        model1.performFly();
        model1.setFlyBehavior(new FlyRocketPowered());//动态的改变飞行行为
        model1.performFly();
    }
}

 

posted on 2016-06-11 19:28  紫色年华  阅读(281)  评论(0编辑  收藏  举报

导航