装饰模式又称为包装模式,可以通过一种对客户端透明的方式来扩展对象的功能,是继承关系的一种替换方案。
装饰模式吧要添加的附加功能分别放在单独的类中,并让这个类包含他要装饰的对象,需要执行时,客户端可以选择地,按顺序的使用装饰功能包装对象,比如一个普通手机phone,添加一个拍照功能成了一个photo_phone,在此基础上再加一个播放音乐功能就成了一个又能拍照又能播放音乐的music_phone,当然还可以继续添加功能
#include <iostream>
using namespace std;
class Phone
{
public:
virtual void Function()=0;
};
class CallPhone:public Phone
{
public:
void Function()
{
cout<<"能打电话的手机"<<endl;
}
};
class PhotoPhone:public Phone
{
private:
Phone *phone;
public:
PhotoPhone(Phone *p)
{
phone = p;
}
void Function()
{
phone->Function();
cout<<"能拍照的手机"<<endl;
}
};
class MusicPhone:public Phone
{
private:
Phone *phone;
public:
MusicPhone(Phone *p)
{
phone = p;
}
void Function()
{
phone->Function();
cout<<"能听音乐的手机"<<endl;
}
};
class InternetPhone:public Phone
{
private:
Phone *phone;
public:
InternetPhone(Phone *p)
{
phone = p;
}
void Function()
{
phone->Function();
cout<<"能上网的手机"<<endl;
}
};
int main()
{
Phone *call_phone = new CallPhone;
call_phone -> Function();
//cout<<"************"<<endl;
cout<<endl;
Phone *photo_phone = new PhotoPhone(call_phone);
photo_phone -> Function();
cout<<endl;
Phone *music_phone = new MusicPhone(photo_phone);
music_phone -> Function();
cout<<endl;
Phone *smart_phone = new InternetPhone(music_phone);
smart_phone -> Function();
return 0;
}
主要思想还是依靠继承,先在基类抽象类中留下接口virtual void Function()=0;用来规范准备增加附加功能的对象,然后在接下来的子类中具体实现。