装饰模式

装饰模式

动态(组合)地给一个对象增加一些额外的职责。就增加功能而言,Decorator模式比生成子类(继承)更为灵活(消除重复代码&减少子类个数)。

class Stream
{
public:
  virtual char* read(int size) = 0;
  virtual void write(char* data,int size) = 0;
  virtual void seek(int position) = 0;
}

class FileStream : public Stream
{
public:
  virtual char* read(int size) override
  {
    //...
  }
  virtual void write(char* data,int size) override
  {
    //...
  }
  virtual void seek(int position) override
  {
    //...
  }
}

class NetworkStream : public Stream
{
public:
  virtual char* read(int size) override
  {
    //...
  }
  virtual void write(char* data,int size) override
  {
    //...
  }
  virtual void seek(int position) override
  {
    //...
  }
}

class MemoryStream : public Stream
{
public:
  virtual char* read(int size) override
  {
    //...
  }
  virtual void write(char* data,int size) override
  {
    //...
  }
  virtual void seek(int position) override
  {
    //...
  }
}

class DecoratorStream : public Stream
{
public:
  DecoratorStream(Stream* stream):stream_(stream){ }
  virtual ~DecoratorStream(){ }
  
protected:
  Stream* stream_;
}

class CryptoStreamDecorator : public Stream
{
public:
  virtual char* read(int size) override
  {
    //...
    stream_->read(size);
    //...
  }
  virtual void write(char* data,int size) override
  {
    //...
    stream_->write(data,size);
    //...
  }
  virtual void seek(int position) override
  {
    //...
    stream_->seek(position);
    //...
  }
}

class BufferStreamDecorator : public Stream
{
public:
  virtual char* read(int size) override
  {
    //...
    stream_->read(size);
    //...
  }
  virtual void write(char* data,int size) override
  {
    //...
    stream_->write(data,size);
    //...
  }
  virtual void seek(int position) override
  {
    //...
    stream_->seek(position);
    //...
  }
}

int main()
{
  FileStream* fs=new FileStream();
  CryptoStreamDecorator csd=new CryptoStreamDecorator(fs);
  BufferStreamDecorator bsd=new BufferStreamDecorator(csd);
  bsd->read(10);
  bsd->seek(0);
  bs->write("hello world!",13);
}

UML类图

装饰模式

上一篇:桥接模式


下一篇:设计模式- 开闭原则