码迷,mamicode.com
首页 > 编程语言 > 详细

大话设计模式--装饰模式 C++简单例子

时间:2018-07-27 23:17:57      阅读:269      评论:0      收藏:0      [点我收藏+]

标签:设计   执行   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;
}

 

大话设计模式--装饰模式 C++简单例子

标签:设计   执行   null   col   rate   ++   new   on()   res   

原文地址:https://www.cnblogs.com/hustwx/p/9379971.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!