decorator 装饰模式
装饰模式指的是在不必改变原类文件和使用继承的情况下,动态地扩展一个对象的功能。它是通过创建一个包装对象,也就是装饰来包裹真实的对象。重要的一点是装饰器既有基类的多态指针又继承于基类
/**
* 流基类
*/
class stream
{
public:
virtual void read()=0;
virtual void write()=0;
virtual void seek()=0;
};
/**
* 文件流
*/
class fileStream : public stream
{
virtual void read()
{
cout<<"文件读取"<<endl;
}
virtual void write()
{
cout<<"文件写"<<endl;
}
virtual void seek()
{
cout<<"文件随机"<<endl;
}
};
/**
* 网络流
*/
class netStream : public stream
{
virtual void read()
{
cout<<"网络读取"<<endl;
}
virtual void write()
{
cout<<"网络写"<<endl;
}
virtual void seek()
{
cout<<"网络随机"<<endl;
}
};
/*
* 装饰器
*/
class decorator : public stream
{
public:
decorator(stream* _st):st(_st){}
protected:
stream* st;
};
//缓存装饰
class cacheDecorator : public decorator
{
public:
cacheDecorator(stream* _st):decorator(_st){}
virtual void read()
{
st->read();
cout<<"缓存读"<<endl;
}
virtual void write()
{
st->write();
cout<<"缓存写"<<endl;
}
virtual void seek()
{
st->seek();
cout<<"缓存随机"<<endl;
}
};
//加密装饰
class decryptDecorator : public decorator
{
public:
decryptDecorator(stream* _st):decorator(_st){}
virtual void read()
{
st->read();
cout<<"加密读"<<endl;
}
virtual void write()
{
st->write();
cout<<"加密写"<<endl;
}
virtual void seek()
{
st->seek();
cout<<"加密随机"<<endl;
}
};
#include <iostream>
using namespace std;
int main(int argc, char const *argv[]) {
fileStream* file = new fileStream();
netStream* net = new netStream();
//缓存
cacheDecorator* cache = new cacheDecorator(file);
decryptDecorator* decript = new decryptDecorator(net);
cache->read();
cache->write();
decript->read();
decryptDecorator* decript1 = new decryptDecorator(cache);
decript1->read();
decript1->seek();
return 0;
}
我觉得这个设计模式最重要的就是装饰器中既有基类的多态指针,又继承基类。让装饰器可以不断地改变对象功能并且保持对象不变。