码迷,mamicode.com
首页 > 其他好文 > 详细

Strategy - 策略模式

时间:2016-10-27 23:29:32      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:style   class   abstract   eve   font   public   ann   使用   blog   

策略模式: 定义了算法族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化独立于使用算法的客户。
public
interface FlyBehavior { public void fly(); }
public class FlyWithWings implements FlyBehavior{

    @Override
    public void fly() {
        System.out.println("i‘m flying");
        
    }

}

public class FlyNoWay implements FlyBehavior{

    @Override
    public void fly() {
        System.out.println(" cannot fly");
        
    }

}
public interface QuackBehavior {

    public void quack();
}
public class Quack implements QuackBehavior{

    @Override
    public void quack() {
        System.out.println("quack");
        
    }

}
public class MuteQuack implements QuackBehavior{

    @Override
    public void quack() {
        System.out.println("<<silence>>");
        
    }

}
public class Squeak implements QuackBehavior{

    @Override
    public void quack() {
        System.out.println("squeak");
        
    }

}
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 FlyBehavior getFlyBehavior() {
        return flyBehavior;
    }

    public void setFlyBehavior(FlyBehavior flyBehavior) {
        this.flyBehavior = flyBehavior;
    }

    public QuackBehavior getQuackBehavior() {
        return quackBehavior;
    }

    public void setQuackBehavior(QuackBehavior quackBehavior) {
        this.quackBehavior = quackBehavior;
    }
    
    
}
public class MallardDuck extends Duck{

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

    @Override
    public void display() {
        System.out.println("I am  a mallard duck");
        
    }

}
public class MiniDuckSimulator {

    public static void main(String[] args){
        Duck mallard = new  MallardDuck();
        mallard.performFly();
        mallard.performQuack();
        
        mallard.setFlyBehavior(new FlyNoWay());
        mallard.performFly();
    }
}
public class MiniDuckSimulator {

    public static void main(String[] args){
        Duck mallard = new  MallardDuck();
        mallard.performFly();
        mallard.performQuack();
        
        mallard.setFlyBehavior(new FlyNoWay());
        mallard.performFly();
    }
}

 

Strategy - 策略模式

标签:style   class   abstract   eve   font   public   ann   使用   blog   

原文地址:http://www.cnblogs.com/ly-radiata/p/6005801.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!