设计模式(7)---结构型之装饰模式

1 概念
装饰(Decorator )模式又叫做包装模式。通过一种对客户端透明的方式来扩展对象的功能,是继承关系的一个替换方案。

装饰模式就是把要添加的附加功能分别放在单独的类中,并让这个类包含它要装饰的对象,当需要执行时,客户端就可以有选择地、按顺序地使用装饰功能包装对象。

2适用于:
装饰者模式(Decorator Pattern)动态的给一个对象添加一些额外的职责。就增加功能来说,此模式比生成子类更为灵活。

#ifndef _PHONE_H_
#define _PHONE_H_
class Phone
{
public:
Phone(){}
virtual ~Phone(){}
virtual void ShowPhone() = 0;
};
class NokiaPhone:public Phone
{
public:
NokiaPhone(){}
~NokiaPhone(){}
void ShowPhone();
};
class IPhone :public Phone
{
public:
IPhone(){}
~IPhone(){}
void ShowPhone();
};
class DecoratorPhone :public Phone
{
public:
DecoratorPhone(Phone *ph);
~DecoratorPhone(){}
virtual void ShowPhone() = 0;
private:
Phone *m_ph;
};
class DecoratorPhoneA :public Phone
{
public:
DecoratorPhoneA(Phone *ph);
~DecoratorPhoneA(){}
virtual void ShowPhone();
private:
Phone *m_ph;
};
class DecoratorPhoneB :public Phone
{
public:
DecoratorPhoneB(Phone *ph);
~DecoratorPhoneB(){}
virtual void ShowPhone();
private:
Phone *m_ph;
};
#endif

#include"phone.h"
#include
	#include
using namespace std;
void NokiaPhone::ShowPhone()
{
cout << "this is NokiaPhone." << endl;
}
void IPhone::ShowPhone()
{
cout << "this is IPhone." << endl;
}

DecoratorPhoneA::DecoratorPhoneA(Phone *ph)
{
m_ph = ph;
}


void DecoratorPhoneA::ShowPhone()
{
m_ph->ShowPhone();
cout << "ÎÒÒªÌùĤ¡£" << endl;
}
DecoratorPhoneB::DecoratorPhoneB(Phone *ph)
{
m_ph = ph;
}
void DecoratorPhoneB::ShowPhone()
{
m_ph->ShowPhone();
cout << "ÎÒÒª»»¿Ç¡£" << endl;
}

#include"phone.h"
int main()
{
Phone *ph1 = new NokiaPhone;
DecoratorPhoneA *DA = new DecoratorPhoneA(ph1);
DecoratorPhoneB *DB = new DecoratorPhoneB(ph1);
DA->ShowPhone();
DB->ShowPhone();
delete ph1;
delete DA;
delete DB;
return 1;
}

你可能感兴趣的:(C++,设计模式)