1. 程式人生 > >大話設計模式--裝飾模式 C++簡單例子

大話設計模式--裝飾模式 C++簡單例子

span 例子 簡單例子 new pre virt != code decorator

裝飾模式在對象動態增加功能方面優於繼承,用裝飾模式替代繼承,比繼承更加靈活。

小菜扮靚第三版

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; }

大話設計模式--裝飾模式 C++簡單例子