现在的位置: 首页 > 自动控制 > 工业·编程 > 正文

代码版设计模式9:装饰模式【结构型】

2013-02-26 12:11 工业·编程 ⁄ 共 1250字 ⁄ 字号 暂无评论

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

//
struct IPhone
{
public:
    IPhone() { }
    virtual ~IPhone() { }

    virtual void ShowDecorate() = 0;
};

class CApplePhone : public IPhone
{
public:
    CApplePhone(string name) : m_name(name) { }
    virtual ~CApplePhone() { }

    virtual void ShowDecorate() { cout<<m_name<<" "; }

private:
    string m_name;
};

class CNokiaPhone : public IPhone
{
public:
    CNokiaPhone(string name) : m_name(name) { }
    virtual ~CNokiaPhone() { }

    virtual void ShowDecorate() { cout<<m_name<<" "; }

private:
    string m_name;
};

//
struct IDecorate : public IPhone
{
public:
    IDecorate(IPhone *pPhone) : m_pPhone(pPhone) { }
    virtual ~IDecorate() { }

    virtual void ShowDecorate() { m_pPhone->ShowDecorate(); }

private:
    IPhone *m_pPhone;
};

class CDecorateA : public IDecorate
{
public:
    CDecorateA(IPhone *pPhone) : IDecorate(pPhone) { }
    virtual ~CDecorateA() { }

    virtual void ShowDecorate() { IDecorate::ShowDecorate(); AddDecorate();  }

private:
    void AddDecorate() { cout<<"挂件"<<endl; }
};

class CDecorateB : public IDecorate
{
public:
    CDecorateB(IPhone *pPhone) : IDecorate(pPhone) { }
    virtual ~CDecorateB() { }

    virtual void ShowDecorate() { IDecorate::ShowDecorate(); AddDecorate(); }

private:
    void AddDecorate() { cout<<"贴膜"<<endl; }
};

//
void main()
{
    CApplePhone Phone("apple");

    CDecorateA decorate(&Phone);

    decorate.ShowDecorate();
}

给我留言

留言无头像?