容許向一個現有的對象添加新的功能,同時又不改變其結構。這種設計類型屬於結構性模式,它是做爲現有類的一個包裝設計模式
這種設計模式建立了一個裝飾類,用來包裝原有的類,並在保持類方法簽名完整的前提下,提供額外的功能。this
何使使用裝飾器: 在不想增長子類的狀況下,擴展類spa
優勢:裝飾類和被裝飾類能夠獨立發展,不會相互耦合,裝飾模式是繼承的一個替代模式,裝飾模式能夠動態擴展一個實現類的功能。設計
缺點:多層裝飾比較複雜。code
使用場景: 一、擴展一個類的功能。 二、動態增長功能,動態撤銷。component
//基礎接口 public interface Component { public void biu(); } //具體實現類 public class ConcretComponent implements Component { public void biu() { System.out.println("biubiubiu"); } } //裝飾類 public class Decorator implements Component { public Component component; public Decorator(Component component) { this.component = component; } public void biu() { this.component.biu(); } } //具體裝飾類 public class ConcreteDecorator extends Decorator { public ConcreteDecorator(Component component) { super(component); } public void biu() { System.out.println("ready?go!"); this.component.biu(); } }
//使用裝飾器 Component component = new ConcreteDecorator(new ConcretComponent()); component.biu(); //console: ready?go! biubiubiu