装饰模式-c++

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

class Phone
{
public:
    Phone() {}
    virtual ~Phone() {}
    virtual void ShowDecorate() {}
};
//具体的手机类
class NokiaPhone : public Phone
{
private:
    string m_name;
public:
    NokiaPhone(string name) : m_name(name) {}
    ~NokiaPhone() {}
    void ShowDecorate() { cout << m_name << "" << endl; }
};
//装饰类
class DecoratorPhone : public Phone
{
private:
    Phone *m_phone;  //要装饰的手机
public:
    DecoratorPhone(Phone *phone) : m_phone(phone) {}
    virtual void ShowDecorate() { m_phone->ShowDecorate(); }
};
//具体的装饰类
class DecoratorPhoneA : public DecoratorPhone
{
public:
    DecoratorPhoneA(Phone *phone) : DecoratorPhone(phone) {}
    void ShowDecorate() { DecoratorPhone::ShowDecorate(); AddDecorate(); }
private:
    void AddDecorate() { cout << "手机来电声音" << endl; } //增加的装饰
};
//具体的装饰类
class DecoratorPhoneB : public DecoratorPhone
{
public:
    DecoratorPhoneB(Phone *phone) : DecoratorPhone(phone) {}
    void ShowDecorate() { DecoratorPhone::ShowDecorate(); AddDecorate(); }
private:
    void AddDecorate() { cout << "手机来电震动" << endl; } //增加的装饰
};
//具体的装饰类
class DecoratorPhoneC : public DecoratorPhone
{
public:
    DecoratorPhoneC(Phone *phone) : DecoratorPhone(phone) {}
    void ShowDecorate() { DecoratorPhone::ShowDecorate(); AddDecorate(); }
private:
    void AddDecorate() { cout << "手机来电闪烁灯提示" << endl; } //增加的装饰
};
int main()
{
    Phone *iphone = new NokiaPhone("SimplePhone");
    Phone *dpa = new DecoratorPhoneA(iphone);
    dpa->ShowDecorate();
    cout << "***********" << endl<<endl;
    Phone *phone = new NokiaPhone("JarPhone");
    Phone *dpA = new DecoratorPhoneA(phone);
    Phone *dpb = new DecoratorPhoneB(dpA);
    dpb->ShowDecorate();
    cout << "***********" << endl << endl;
    Phone *cphone = new NokiaPhone("ComplexPhone");
    Phone *d = new DecoratorPhoneA(cphone);
    Phone *dpB = new DecoratorPhoneB(d);
    Phone *dpC = new DecoratorPhoneC(dpB);
    dpC->ShowDecorate();

    delete dpa;
    delete iphone;

    delete dpA;
    delete dpb;
    delete phone;

    delete d;
    delete dpB;
    delete dpC;
    delete cphone;
}

 

posted @ 2021-10-16 16:19  yasai  阅读(31)  评论(0编辑  收藏  举报