五、裝飾模式

顧名思義,裝飾模式就是給一個(gè)對(duì)象增加一些新的功能,而且是動(dòng)態(tài)的,要求裝飾對(duì)象和被裝飾對(duì)象實(shí)現(xiàn)同一個(gè)接口,裝飾對(duì)象持有被裝飾對(duì)象的實(shí)例。

Source類是被裝飾類,Decorator類是一個(gè)裝飾類,可以為Source類動(dòng)態(tài)的添加一些功能,代碼如下:

public interface Sourceable { 
 public void method(); 
}

public class Source implements Sourceable { 
 @Override 
 public void method() { 
   System.out.println("the original method!"); 
 } 
}

public class Decorator implements Sourceable {  
 private Sourceable source;    
 public Decorator(Sourceable source){ 
   super(); 
   this.source = source; 
 } 
 @Override 
 public void method() { 
   System.out.println("before decorator!"); 
   source.method(); 
   System.out.println("after decorator!"); 
 } 
}

測(cè)試類:

public class DecoratorTest {  
  public static void main(String[] args) { 
    Sourceable source = new Source(); 
    Sourceable obj = new Decorator(source); 
    obj.method(); 
  } 
}

輸出:

before decorator!
the original method!
after decorator!

裝飾器模式的應(yīng)用場(chǎng)景:

  1. 需要擴(kuò)展一個(gè)類的功能。
  2. 動(dòng)態(tài)的為一個(gè)對(duì)象增加功能,而且還能動(dòng)態(tài)撤銷。(繼承不能做到這一點(diǎn),繼承的功能是靜態(tài)的,不能動(dòng)態(tài)增刪)

缺點(diǎn):
產(chǎn)生過(guò)多相似的對(duì)象,不易排錯(cuò)!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容