装饰模式:动态地给一个对象添加一些额外的职责。增加功能来说,装饰模式相比生成子类 更为灵活。有时我们希望给某个对象而不是整个类添加一些功能。比如有一个手机,允许你为手机添加特性,比如增加挂件、屏幕贴膜等。一种灵活的设计方式是, 将手机嵌入到另一对象中,由这个对象完成特性的添加,我们称这个嵌入的对象为装饰。这个装饰与它所装饰的组件接口一致,因此它对使用该组件的客户透明。
#include <iostream>
#include <string>
using namespace std;
class Phone
{
public:
Phone() {}
virtual ~Phone() {}
virtual void ShowDecorate() {}
};
class iPhone:public Phone
{
private:
string m_name;
public:
iPhone(string name):m_name(name){}
~iPhone() {}
void ShowDecorate()
{
cout << m_name << "的装饰" <<endl;
}
};
class AndroidPhone : public Phone
{
private:
string m_name;
public:
AndroidPhone(string name):m_name(name){}
~AndroidPhone() {}
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;
}
};
int main()
{
Phone *dpa = new DecoratorPhoneA(new iPhone("5s"));
dpa->ShowDecorate();
delete dpa;
Phone *dpb = new DecoratorPhoneA(new AndroidPhone("Mi2s"));
dpb->ShowDecorate();
system("pause");
return 0;
}