裝飾器模式

定義:

  動態的給一個對象增加一些額外的職責,就增加功能來說,裝飾模式比生成子類更為靈活。

  就是以組合的方式動態的為對象添加功能,比起繼承,更符合開閉原子。

結構圖:

 

 

 程式碼:

//Component類

class Component

{

public:

//抽象核心職責,裝飾器需要在這個職責基礎上增加新的職責

  public void operation();

}

//Component實現類

class ConcreteComponent  : Component

{

//核心職責實現

public:

   void operation()

  {

    。。。;

  }

}

//裝飾器抽象類,需要有一個成員指向組件對象,並含有組件核心職責介面定義

class Decorator : Component

{

protected: 

//指向組件對象的成員

  ConcreteComponent  cConcreteComponent;

public  :

//構造方法傳入組件對象

  Decorator :Decorator (ConcreteComponent  cConcreteComponent)

  {

    this.cConcreteComponent = cConcreteComponent;

  }

//j組件核心職責

  void operation()

  {

   cConcreteComponent .operation();

  }

]

//具體裝飾A

class DecoratorA : Decorator

{

public:

//新增功能

  void Addoperation 

  {

    。。。;

  }

//組件核心職責

  void operation()

  {

     Addoperation();//增加新職責

   this.cConcreteComponent .operation();

  }

}

//具體裝飾B

class DecoratorB: Decorator

{

public:

//新增功能

  void AddBoperation 

  {

    。。。;

  }

//j組件核心職責

  void operation()

  {

     AddBoperation();//增加新職責

   this.cConcreteComponent .operation();

  }

}

//客戶端

Component cConcreteComponent = new ConcreteComponent();

DecoratorA cDecoratorA = new DecoratorA (cConcreteComponent );

DecoratorB cDecoratorB = new DecoratorB (cDecoratorA );

cDecoratorB .operation();

 

使用時機:

  當系統需要新增功能,並且新增功能是為了裝飾原有核心職責或者主要行為時,考慮裝飾器模式。

 

優點:把類中的裝飾功能從類中搬移出去,簡化原有的類,並守護開閉原則

缺點:更多的類,使程式更加複雜。