Strategy - 策略模式

Posted 如何静

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Strategy - 策略模式相关的知识,希望对你有一定的参考价值。

策略模式: 定义了算法族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化独立于使用算法的客户。
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 - 策略模式的主要内容,如果未能解决你的问题,请参考以下文章

22-策略(Strategy)模式Ruby实现

设计模式之- 策略模式(Strategy Pattern)

Java设计模式之策略模式(Strategy)

1.Strategy Pattern(策略模式)

设计模式:Strategy(策略)

23种设计模式之策略模式(Strategy)