场景:创建各种鸭子
概念:
设计原则:
1.抽取变化之处
2.对接口编程
3.多用组合少用继承
UML 图:
代码:
// FlyBehavior ===================================================== public interface FlyBehavior { public void fly(); } public class FlyNoWay implements FlyBehavior { @Override public void fly() { System.out.println("I cannot fly");} } public class FlyWithWings implements FlyBehavior { @Override public void fly() { System.out.println("I'm flying !!"); } } // QuackBehavior ===================================================== public interface QuackBehavior { public void quack(); } public class MuteQuack implements QuackBehavior { @Override public void quack() { System.out.println("quack.MuteQuack"); } } public class Quack implements QuackBehavior { @Override public void quack() { System.out.println("Quack"); } } public class Squeak implements QuackBehavior { @Override public void quack() { System.out.println("quack.Squeak"); } } // Duck ================================================================== 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 setFlyBehavior(FlyBehavior fb) { flyBehavior = fb; } public void setQuackBehavior(QuackBehavior qb) { quackBehavior = qb; } public void swim() { // 所有的鸭子漂浮,甚至诱饵鸭! System.out.println("all ducks float, even decoys!"); } } public class MallardDuck extends Duck { public MallardDuck() { quackBehavior = new Quack(); flyBehavior = new FlyWithWings(); } @Override public void display() { System.out.println("I'm a real mallard duck");} } // test ================================================================== public class MiniDuckSimulator { public static void main(String[] args) { Duck mallard = new MallardDuck(); mallard.performQuack(); mallard.performFly(); // 动态设定行为 mallard.setFlyBehavior(new FlyNoWay()); mallard.performFly(); } } // 输出: // Quack // I'm flying !! // I cannot fly
有价值的问答:
全文完。