主要區(qū)別:使用代理模式,代理和真實對象之間的的關(guān)系通常在編譯時就已經(jīng)確定了,而裝飾者能夠在運行時遞歸地被構(gòu)造。
自己理解:代理模式的存在是純粹的功能增強;而裝飾者模式有自己的基本大類分類(如披薩,意大利面,焗飯等,裝飾的只是調(diào)味料而已,如鹽,沙拉醬,糖等,拿java.io舉例,它有基本的io類如:stringbufferinputstream, fileinputstream等,而filterinputstream中就是一堆調(diào)味料,可自行無限組合添加,pushbackinputstream,bufferinputestream等),裝飾著模式最大的目的在于極有很多小功能而且相互之間可以無限制組合,將它們?nèi)坑啚檠b飾者,可以自由靈活隨意組合使用,不用為每一種組合定義一個類去實現(xiàn)。@@裝飾著模式為了功能組合增強,代理模式只是純粹的增強@@
代理模式示例:
//代理模式
public class Proxy implements Subject{
private Subject subject;
public Proxy(){
//關(guān)系在編譯時確定
subject = new RealSubject();
}
public void doAction(){
….
subject.doAction();
….
}
}
//代理的客戶
public class Client{
public static void main(String[] args){
//客戶不知道代理委托了另一個對象
Subject subject = new Proxy();
…
}
}
而裝飾者模式:(是不是和java.io.下的代碼很相似)
//裝飾器模式
public class Decorator implements Component{
private Component component;
public Decorator(Component component){
this.component = component
}
public void operation(){
….
component.operation();
….
}
}
public class Client{
public static void main(String[] args){
//客戶指定了裝飾者需要裝飾的是哪一個類
Component component = new Decorator(new ConcreteComponent());
…
}
}