设计模式——装饰器模式(decorator)

Decorator,Bridge属於单一职责模式。

motivation:过度使用继承来扩展对象的功能,由于继承为类型引入了静态特性,是的这种扩展缺乏灵活性;并且随着子类的增多,更多子类的组合会导致更多子类的膨胀。(使用组合优于继承的设计原则)

上图的众多子类经过重构之后,形成下图子类较少,更易维护的结构。

key interface or class:

        1.实现基类的类型,如FileStream,NetWorkStream,MemoryStream;

        2.装饰类,用于对基本类型进行功能的扩展。

feature:在装饰类中既继承基类,也有基类的成员(某些实现)。

structure:

 

template codes:

//基类
class Stream{
public:
    virtual void Read()=0;
    virtual void Write()=0;
    virtual void Seak()=0;

    virtual ~Stream(){};
}


//不同类别的实现
class FileStream: public Stream{
    //实现接口
}
class MemoryStream: public Stream{
    //实现接口
}
class NetworkStream: public Stream{
    //实现接口
}

//实现扩展功能的装饰类
class CryptoStream: public Stream{
    //构造时可以设为FileStream,MemoryStream,NetworkStream等
    //根据要实现扩展的对象
    Stream* stream;
public:
    CryptoStream(Stream* stream){
        this->stream = stream;
    }

    virtual void Read(){
        //此处增加额外的Crypto操作
        stream->Read();
    }
    virtual void Write(){
        //此处增加额外的Crypto操作
        stream->Write();
    }
    virtual void Seak(){
        //此处增加额外的Crypto操作
        stream->Seak();
    }
}
class BufferStream: public Stream{
    //与上相似
}
class CryptoBufferStream: public Stream{
    //与上相似
}



//调用
void process(){
    Stream* fs = new FileStream();
    Stream* ms = new MemoryStream();
    Stream* ns = new NetworkStream();

    //给不同Stream类扩展新功能——实现运行时装配
    CryptoStream* cptFs = new CryptoStream(fs); //给fs增加Crypto功能
    BufferStream* bfrFs = new BufferStream(fs); //给fs增加buffer功能
    CryptoBufferStream* cbFs = new CryptoBufferStream(fs); //给fs增加crypto和buffer功能
    BufferStream* bCptFs = new BufferStream(cptFs); //给cptFs增加buffer功能
}



//为了实现对装饰器类中Stream*字段的复用,可以将该重复字段上提,但由于该字段为基类Stream本身
//所遇你经常可以,设置一个中间类来复Stream*字段,使装饰类都继承自该中间类
class decoratorStream: public Stream{
protect:
    Stream* stream;
    decoratorStream(Stream* stm): stream(stm){
    }
}
class CryptoStream: public decoratorStream{
public:
    //...
}

summary:

1. 采用组合而非继承的手法,decorator模式在运行时动态扩展对象的功能,避免了使用继承造成的不灵活和子类众多的问题;

2.decorator模式在接口上表现出is-a的继承关系,即decorator类继承自接口component,同时在实现上又表现出has-a的组合关系,即decorator类中组合了一个component类;

3.decorator模式并非主要解决子类繁衍问题,主要是为了实现主体类在多方向功能扩展的功能(即主体操作和分支操作应该分支分开继承)。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章