标签:客户 ext void 替换 owa class mini with ace
模拟鸭子游戏SimUDuck
设计原则: 找出应用中需要变化之处,把它们独立出来,不需要和那些变化的代码混在一起
设计原则: 针对接口编程,而不是针对实现编程
设计原则: 多用组合,少用继承
策略模式定义: 定义了算法族,分别封装起来,让他们之间可以相互替换,此模式让算法的变化独立于使用算法的客户
1 public class MiniDuckSimulator 2 { 3 public static void main(String[] args) 4 { 5 //绿头鸭 6 Duck mallard = new MallardDuck(); 7 mallard.performQuack(); 8 mallard.performFly(); 9 10 System.out.println("----------------"); 11 12 13 //模型鸭 14 Duck model = new ModelDuck(); 15 model.performFly(); 16 model.setFlyBehavior(new FlyRocketPowered()); 17 model.performFly(); 18 } 19 } 20 //鸭子抽象类 21 abstract class Duck{ 22 FlyBehavior flyBehavior; 23 QuackBehavior quackBehavior; 24 public Duck() { 25 26 27 } 28 29 public abstract void display(); 30 //还有更多 31 32 public void performFly() { 33 flyBehavior.fly(); 34 } 35 36 public void performQuack() { 37 quackBehavior.quack(); 38 } 39 40 public void swim() { 41 System.out.println("All ducks float, even decoys!"); 42 } 43 44 public void setFlyBehavior(FlyBehavior fb) { 45 flyBehavior = fb; 46 } 47 48 public void setQuackBehavior(QuackBehavior qb) { 49 quackBehavior = qb; 50 } 51 } 52 //飞行行为 53 interface FlyBehavior { 54 public void fly(); 55 } 56 //用翅膀飞 57 class FlyWithWings implements FlyBehavior { 58 public void fly() { 59 System.out.println("I‘m flying!!"); 60 } 61 } 62 //不会飞 63 class FlyNoWay implements FlyBehavior { 64 public void fly() { 65 System.out.println("I can‘t fly."); 66 } 67 } 68 //以火箭为动力 69 class FlyRocketPowered implements FlyBehavior { 70 public void fly() { 71 System.out.println("I‘m flying with a rocket!"); 72 } 73 } 74 75 //叫行为 76 interface QuackBehavior { 77 public void quack(); 78 } 79 // 80 class Quack implements QuackBehavior { 81 public void quack(){ 82 System.out.println("Quack"); 83 } 84 } 85 //不会叫 86 class MuteQuack implements QuackBehavior { 87 public void quack() { 88 System.out.println("<< Silence >>"); 89 } 90 } 91 // 92 class Squeak implements QuackBehavior { 93 public void quack() { 94 System.out.println("Squeak"); 95 } 96 } 97 //绿头鸭 98 class MallardDuck extends Duck { 99 public MallardDuck() { 100 quackBehavior = new Quack(); 101 flyBehavior = new FlyWithWings(); 102 } 103 104 public void display() { 105 System.out.println("I‘m a real Mallad duck"); 106 } 107 } 108 109 //模型鸭 110 class ModelDuck extends Duck { 111 public ModelDuck() { 112 flyBehavior = new FlyNoWay(); 113 quackBehavior = new Quack(); 114 } 115 116 public void display() { 117 System.out.println("I‘m a model duck"); 118 } 119 }
类似的:每个角色一次只能使用一个武器,但是可以 在游戏的过程中换武器。
标签:客户 ext void 替换 owa class mini with ace
原文地址:http://www.cnblogs.com/8386blogs/p/7465266.html