首页 > 代码库 > 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 - 策略模式
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。