欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

c++装饰模式

程序员文章站 2022-07-03 08:41:55
c++装饰模式 #include #include using namespace std; class Person { private: stri...
c++装饰模式
#include 
#include 
using namespace std;
class Person
{
private:
    string m_strName;
public:
    Person(string strName)
    {
        m_strName = strName;
    }
    Person(){}
    virtual void Show()
    {
        cout<<"装扮的是:"<
    }
};
//装饰类
class Finery : public Person
{
protected:
    Person* m_component;
public:
    void Decorate(Person* component)
    {
        m_component = component;
    }
    virtual void Show()
    {
        m_component->Show();
    }
};
//T
class TShirts : public Finery
{
public:
    virtual void Show()
    {
        cout<<"穿件TShirts"<
        m_component->Show();
    }
};
//裤子
class BigTrouser : public Finery
{
public:
    virtual void Show()
    {
        cout<<"穿件裤子"<
        m_component->Show();
    }
};
class Glass : public Finery
{
public:
    virtual void Show()
    {
        cout<<"哥再戴个墨镜"<
        m_component->Show();
    }
};
int main()
{
    Person* p = new Person("海涛");
    BigTrouser* bt = new BigTrouser();
    TShirts* ts = new TShirts();
    Glass* gl = new Glass();
    //拿裤子装饰“裸人”
    bt->Decorate(p);
    //拿TShirts装饰穿了裤子的人
    ts->Decorate(bt);
    //让穿着裤子Tshirts的人戴墨镜
    gl->Decorate(ts);
    gl->Show();
    return 0;
}
//?天太热,哥只想戴墨镜和穿裤子怎么办?
//gl->Decorate(bt);
//?只想穿TShirt和戴墨镜又怎么办?
//ts->Decorate(p);
//gl->Decorate(ts);
//是不是很灵活?

 

上一篇: OCM成长之旅

下一篇: Oracle基础知识