装饰者模式:动态地给一个对象添加一些额外的功能。有时我们希望给某个对象而不是整个类添加一些功能。
作为装饰者,需要先将需要装饰的对象传入装饰类中,知道需要对谁进行装饰。
Decorator(Phone* phone)
1、为什么Decorator装饰者需要继承Phone类,而不是其他的类,或者不继承?
作为装饰者,仍相当于跟NokiaPhone类同级,只是在这种类的某个功能上添加新的功能,
这样可以由多态通过Phone调用派生类Show函数时,调用到装饰者派生类函数
2、为什么不直接在派生类中添加功能?
装饰者派生类与实物派生类会构成(n*n)中可能,有新的装饰需要添加时,n个实物派生类都需要添加
#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
class Phone
{
public:
virtual void Show() = 0;
};
class iPhone : public Phone
{
public:
iPhone(string strName) : m_strName(strName){}
~iPhone(){}
public:
void Show()
{
cout<<m_strName<<endl;
}
private:
string m_strName;
};
class NokiaPhone : public Phone
{
public:
NokiaPhone(string strName):m_strName(strName){}
~NokiaPhone(){}
public:
void Show()
{
cout<<m_strName<<endl;
}
private:
string m_strName;
};
class Decorator : public Phone
{
public:
Decorator(Phone* phone) : m_pPhone(phone){}
~Decorator(){}
public:
virtual void Show()
{
m_pPhone->Show();
}
private:
Phone *m_pPhone;
};
class DecotatorPhoneA : public Decorator
{
public:
DecotatorPhoneA(Phone* phone):Decorator(phone){}
~DecotatorPhoneA(){}
public:
void Show()
{
Decorator::Show(); //已有功能
AddDecotator(); //添加新装饰
}
private:
inline void AddDecotator() //添加额外装饰
{
cout<<"DecotatorPhoneA 装饰"<<endl;
}
};
class DecotatorPhoneB : public Decorator
{
public:
DecotatorPhoneB(Phone* phone):Decorator(phone){}
~DecotatorPhoneB(){}
public:
void Show()
{
Decorator::Show();
AddDecotator();
}
private:
inline void AddDecotator() //添加额外装饰
{
cout<<"DecotatorPhoneB 装饰"<<endl;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Phone *phone = new iPhone("ipone");
if (NULL!=phone)
{
Phone *pDePhone = new DecotatorPhoneA(phone);
if (NULL!=pDePhone)
{
pDePhone->Show();
delete pDePhone;
pDePhone = NULL;
}
delete phone;
phone = NULL;
}
return 0;
}