C++设计模式:装饰模式

装饰模式:动态地给一个对象添加一些格外的职责,这个只是对某个对象添加,而不是对整个类。就添加功能来说,装饰模式比生成子类更为灵活。

实现思路:定义一个基类,然后定义装饰基类继承基类,然后每一个具体的装饰类都继承装饰基类,在需要装饰的对象上面添加功能。

代码如下:

#include<iostream>
#include<string>
using namespace std;


class person
{
private:
    string name;
public:
    person(){}
    person(string tt){ name = tt; }
    virtual~person(){}
    virtual void showDecorate()
    {
        cout << "打扮: " << name << endl;
    }
};

class DecoratePerson :public person
{
private:
    person*m_person;
public:
    DecoratePerson(person*p)
    {
        m_person = p;
    }
    void showDecorate()
    {
        m_person->showDecorate();
    }
};

class Tshirts :public DecoratePerson
{
public:
    Tshirts(person*p) :DecoratePerson(p)
    {

    }
    void showDecorate()
    {
        DecoratePerson::showDecorate();
        cout << "T恤  ";
    }
};

class Shoes :public DecoratePerson
{
public:
    Shoes(person*p) :DecoratePerson(p)
    {

    }

    void showDecorate()
    {
        DecoratePerson::showDecorate();
        cout << "鞋子  ";
    }

};



class pants :public DecoratePerson
{
public:
    pants(person*p) :DecoratePerson(p)
    {

    }

    void showDecorate()
    {
        DecoratePerson::showDecorate();
        cout << "裤子  ";
    }
};



int main()
{
    person*curPerson = new person("小明");

    person* decA = new Tshirts(curPerson);
    person*decB = new Shoes(decA);
    person*decC = new pants(decB);


    decC->showDecorate();
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值