1 #include <iostream> 2 using namespace std; 3 4 //设计思想:我们父类和子类就是一个扩展的关系?是不是合适 5 //里氏代换原则:子类对象就应该能完全替代父类的行为 6 //对于继承这样设计,特别小心,我们:组合大于继承 7 //把quack和fly抽象成为一个对象,那么这个问题就了解决方案 8 9 10 ////////////////////////// 11 //完成了将“动作”抽象成“对象” 12 class QuackBehavior { 13 public: 14 virtual void quack() = 0; 15 protected: 16 QuackBehavior(){} 17 }; 18 class FlyBehavior { 19 public: 20 virtual void fly() = 0; 21 protected: 22 FlyBehavior(){} 23 }; 24 25 class FlyWithRocket :public FlyBehavior { 26 void fly() { 27 cout << "做着火箭飞" << endl; 28 } 29 }; 30 31 class FlyWithWings :public FlyBehavior { 32 void fly() { 33 cout << "我有翅膀可以自己飞" << endl; 34 } 35 }; 36 37 class FlyWithNoWay :public FlyBehavior { 38 void fly() { 39 cout << "我根本就会飞" << endl; 40 } 41 }; 42 43 class ZhiZhiQuack :public QuackBehavior { 44 public: void quack() { 45 cout << "吱吱" << endl; 46 } 47 }; 48 49 class PersonQuack :public QuackBehavior { 50 public: 51 void quack() { 52 cout << "我是唐唐姥姥" << endl; 53 } 54 }; 55 56 class WigeonQuack :public QuackBehavior { 57 public: 58 void quack() { 59 cout << "丑小鸭变天鹅" << endl; 60 } 61 }; 62 63 ///////////////////////////////////// 64 //Duck has a Quack 65 // has a Fly 66 class Duck { 67 68 public: 69 70 virtual void Display() = 0; 71 void setFlyBehavior(FlyBehavior* fb) { 72 m_pFly = fb; 73 } 74 void setQuackBehavior(QuackBehavior* qb) { 75 m_pQuack = qb; 76 } 77 78 virtual void perfomrFly() { 79 m_pFly->fly(); 80 81 //if (is 唐老鸭) {唐老鸭的飞行 82 //if (is 小黄鸭){小黄鸭的飞行..... 83 } 84 85 virtual void performQuack() { 86 m_pQuack->quack(); 87 } 88 protected: 89 QuackBehavior *m_pQuack; 90 FlyBehavior *m_pFly; 91 private: 92 }; 93 //DonaladDuck is Duck 94 class DonaladDuck :public Duck { 95 public: 96 DonaladDuck() { 97 m_pFly = new FlyWithRocket;//某一个FlyBehavior的实例 98 m_pQuack = new PersonQuack(); 99 } 100 void Display() { 101 perfomrFly(); 102 performQuack(); 103 } 104 105 }; 106 //第一个困境:子类似乎不太那么像父类。。。 107 class RuberDuck : public Duck { 108 public: 109 RuberDuck() { 110 m_pFly = new FlyWithNoWay(); 111 m_pQuack = new ZhiZhiQuack(); 112 } 113 void Display() { 114 perfomrFly(); 115 performQuack(); 116 } 117 }; 118 119 class WigeonDuck : public Duck { 120 public: 121 WigeonDuck() { 122 m_pFly = new FlyWithWings; 123 m_pQuack = new WigeonQuack; 124 } 125 void Display() { 126 perfomrFly(); 127 performQuack(); 128 } 129 130 }; 131 132 int main() { 133 DonaladDuck *pDonlad = new DonaladDuck; 134 pDonlad->Display(); 135 system("pause"); 136 return 0; 137 } 138 // 139 class XiaoFeiXia :public Duck { 140 // 141 //m_pFly = new FlyWithHotPollun() 142 };strategy.cpp
标签:DonaladDuck,策略,void,模式,strategy,class,pQuack,new,public From: https://www.cnblogs.com/zeliangzhang/p/17897025.html