首页 > 代码库 > Strategy - 策略模式

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 - 策略模式