1.装饰者模式简介
装饰模式指的是在不必改变原类文件和使用继承的情况下,动态地扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对象。
2.源码实现
#include <iostream>
#include <string>
using namespace std;
//抽象构件角色
class Phone
{
public:
virtual void Show() = 0;
};
class iPhone : public Phone
{
public:
iPhone(string strName) : m_strName(strName) {};
~iPhone() {};
void Show()
{
cout << m_strName << endl;
}
private:
string m_strName;
};
class NokiaPhone : public Phone
{
public:
NokiaPhone(string strName) : m_strName(strName) {};
~NokiaPhone() {};
void Show()
{
cout << m_strName << endl;
}
private:
string m_strName;
};
//抽象装饰者角色
class Decorator : public Phone
{
public:
Decorator(Phone *phone) : m_pPhone(phone) {};
~Decorator() {};
virtual void Show()
{
m_pPhone->Show();
}
private:
Phone *m_pPhone;
};
class DecoratorPhoneA : public Decorator
{
public:
DecoratorPhoneA(Phone *phone) : Decorator(phone) {};
~DecoratorPhoneA() {};
void Show()
{
Decorator::Show();
AddDecorator(); //添加新装饰
}
private:
inline void AddDecorator()
{
cout << "DecoratorPhoneA装饰" << endl;
}
};
class DecoratorPhoneB : public Decorator
{
public:
DecoratorPhoneB(Phone *phone) : Decorator(phone) {};
~DecoratorPhoneB() {};
void Show()
{
Decorator::Show();
AddDecorator(); //添加新装饰
}
private:
inline void AddDecorator()
{
cout << "DecoratorPhoneB装饰" << endl;
}
};
int main(int argc, char **argv)
{
//具体构件角色
Phone *phone = new iPhone("iphone");
if(phone == NULL)
{
return -1;
}
//具体装饰者角色
Phone *pDePhone = new DecoratorPhoneA(phone);
if(pDePhone == NULL)
{
delete phone;
return -1;
}
pDePhone->Show();
delete pDePhone;
//具体装饰者角色
pDePhone = new DecoratorPhoneB(phone);
if(pDePhone == NULL)
{
delete phone;
return -1;
}
pDePhone->Show();
delete pDePhone;
delete phone;
return 0;
}
3.编译源码
$ g++ -o example example.cpp
4.运行及其结果
$ ./example
iphone
DecoratorPhoneA装饰
iphone
DecoratorPhoneB装饰
网友评论