装饰模式
装饰模式:动态地给一个对象增加一些额外的职责。就增加功能而言,Decorator模式比生成子类更为灵活。(《设计模式》)
即是通过组合给对象增加功能,可以消除通过继承带来的代码重复和大量子类这些麻烦。通常要扩展对象的功能是用继承的方式实现,但是由于继承为类引入静态特征,一旦扩展的功能增多,子类也会随之增多。所以装饰模式主要用在想要动态扩展功能的情况下。
实现:
1、创建接口
class Stream { public: virtual void read() = 0; virtual void write() = 0; virtual void seek() = 0; virtual ~Stream() {}; };
2、创建接口的实体类
class FileStream :public Stream { // 通过 Stream 继承 read write seek都是静态特征 virtual void read() override; virtual void write() override; virtual void seek() override; }; class NetworkStream : public Stream { // 通过 Stream 继承 virtual void read() override; virtual void write() override; virtual void seek() override; }; void FileStream::read() { cout << __FUNCTION__ << endl; } void FileStream::write() { cout << __FUNCTION__ << endl; } void FileStream::seek() { cout << __FUNCTION__ << endl; } void NetworkStream::read() { cout << __FUNCTION__ << endl; } void NetworkStream::write() { cout << __FUNCTION__ << endl; } void NetworkStream::seek() { cout << __FUNCTION__ << endl; }
3、创建装饰类接口
class DecoratorStream : public Stream { protected: Stream* stream; //组合 public: virtual ~DecoratorStream() {}; };
4、通过继承装饰类接口扩展功能
class CryptoDecoratorStream : public DecoratorStream { public: CryptoDecoratorStream(Stream *stream); // 通过 DecoratorStream 继承 virtual void read() override; virtual void write() override; virtual void seek() override; ~CryptoDecoratorStream(); }; class BufferDecoratorStream : public DecoratorStream { public: BufferDecoratorStream(Stream* stream); // 通过 DecoratorStream 继承 virtual void read() override; virtual void write() override; virtual void seek() override; ~BufferDecoratorStream(); }; CryptoDecoratorStream::CryptoDecoratorStream(Stream* stream) { this->stream = stream; } void CryptoDecoratorStream::read() { stream->read(); cout << "CryptoDecoratorStream" << endl; } void CryptoDecoratorStream::write() { stream->write(); cout << "CryptoDecoratorStream" << endl; } void CryptoDecoratorStream::seek() { stream->seek(); cout << "CryptoDecoratorStream" << endl; } CryptoDecoratorStream::~CryptoDecoratorStream() { delete this->stream; } BufferDecoratorStream::BufferDecoratorStream(Stream* stream) { this->stream = stream; } void BufferDecoratorStream::read() { stream->read(); cout << "BufferDecoratorStream" << endl; } void BufferDecoratorStream::write() { stream->write(); cout << "BufferDecoratorStream" << endl; } void BufferDecoratorStream::seek() { stream->seek(); cout << "BufferDecoratorStream" << endl; } BufferDecoratorStream::~BufferDecoratorStream() { delete this->stream; }
5、使用DecoratorStream来装饰Stream对象
int main() { DecoratorStream* crytoFileStream = new CryptoDecoratorStream(new FileStream); crytoFileStream->read(); DecoratorStream* bufferNetworkStream = new BufferDecoratorStream(new NetworkStream); bufferNetworkStream->write(); delete crytoFileStream; delete bufferNetworkStream; }
DecoratorStream通过组合Stream类,使其子类能够不通过继承就可以为FileStream和NetworkStream扩展功能,减少了子类的个数,也避免了继承带来的大量代码重复。实现了动态扩展功能的需求。