标签:设计 执行 null col rate ++ new on() res
装饰模式在对象动态增加功能方面优于继承,用装饰模式替代继承,比继承更加灵活。
小菜扮靓第三版
class person { public: virtual void show(){ cout << "汤姆: " ; } }; class decorator :public person { public: person *m_a;//被装饰者 void decorate(person* a){ m_a = a; } //void show(){ // if (m_a != nullptr){ // m_a->show(); // } //} }; class Tshirt : public decorator { public: void show(){ m_a->show();//被装饰者先执行 cout << "T恤 "; //decorator::show(); } }; class shores : public decorator { public: void show(){ m_a->show(); cout << "鞋子 "; //decorator::show(); } }; int main() { person *Tom=new person(); Tshirt *Gucci=new Tshirt(); shores *Vans=new shores(); Gucci->decorate(Tom);//Gucci的m_a为person类 Vans->decorate(Gucci);//Vans的m_a为Tshirt类 Vans->show(); return 0; }
小菜扮靓第二版
class person { public: virtual void show(){} }; class Tom : public person { public: void show(){ cout << "汤姆: "; } }; class Jerry : public person { public: void show(){ cout << "杰瑞: "; } }; class decorator :public person { public: person *m_a; void decorate(person* a){ m_a = a; } //void show(){ // if (m_a != nullptr){ // m_a->show(); // } //} }; class Tshirt : public decorator { public: void show(){ m_a->show(); cout << "T恤 "; //decorator::show(); } }; class shores : public decorator { public: void show(){ m_a->show(); cout << "鞋子 "; //decorator::show(); } }; int main() { //person *tom = new Tom(); //Tshirt *Gucci = new Tshirt(); //shores *Vans = new shores(); //Gucci->decorate(tom); //Vans->decorate(Gucci); //Vans->show(); person *jerry = new Jerry(); Tshirt *Gucci = new Tshirt(); shores *Vans = new shores(); Gucci->decorate(jerry); Vans->decorate(Gucci); Vans->show(); return 0; }
标签:设计 执行 null col rate ++ new on() res
原文地址:https://www.cnblogs.com/hustwx/p/9379971.html