设计模式-策略模式
-
定义
策略模式定义了算法族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化独立于使用算法的客户 -
代码实例
interface Quack { void quack(); } interface Fly { void fly(); } class QuackBehavior implements Quack { @Override public void quack() { System.out.println("ga ga ga"); } } class FlyBehavior implements Fly { @Override public void fly() { System.out.println("fly fly fly"); } } abstract class Duck { private Quack quack; private Fly fly; public void setQuack(Quack quack) { this.quack = quack; } public void setFly(Fly fly) { this.fly = fly; } public void performQuack() { quack.quack(); } public void performFly() { fly.fly(); } } class RedheadDuck extends Duck { public RedheadDuck() { super(); this.setQuack(new QuackBehavior()); this.setFly(new FlyBehavior()); } public static void main(String[] args) { Duck redheadDuck = new RedheadDuck(); redheadDuck.performFly(); redheadDuck.performQuack(); } }