1,定義:Attach additional responsibilities to an object dynamically keeping the same interface.Decorators provide a flexible alternative to subclassing for extending functionality. (動態的給一個對象添加其餘職責,就增長功能來講,裝飾模式比生成子類更加靈活)java
2,通用類圖ide
3,實例代碼:flex
/** 抽象組件 **/ public abstract class Component { public abstract void operate(); } /** 具體組件實現類 **/ public class ExecuteComponent extends Component{ @Override public void operate() { System.out.println("我是真正的執行組件"); } } /** 裝飾組件類 **/ public class Decorator extends Component{ private Component component; public Decorator(Component component){ this.component = component; } @Override public void operate() { component.operate(); } } /** 具體裝飾類1 **/ public class ExecuteDecoratorOne extends Decorator{ public ExecuteDecoratorOne(Component component) { super(component); } @Override public void operate() { System.out.println("裝飾類1"); super.operate(); } } /** 具體裝飾類2 **/ public class ExecuteDecoratorTwo extends Decorator{ public ExecuteDecoratorTwo(Component component) { super(component); } @Override public void operate() { System.out.println("裝飾類 2"); super.operate(); } } /** 模式使用 **/ public class Clent { public static void main(String[] args){ Component component = new ExecuteComponent(); Component component1 = new ExecuteDecoratorOne(component); Component component2 = new ExecuteDecoratorTwo(component1); component.operate(); System.out.println("-----------------"); component1.operate(); System.out.println("-----------------"); component2.operate(); } } /** 運行結果 **/ 我是真正的執行組件 ----------------- 裝飾類1 我是真正的執行組件 ----------------- 裝飾類 2 裝飾類1 我是真正的執行組件
4,模式角色this
(1)抽象構件: 一個接口或者抽象類,定義咱們最核心的對象。code
(2)具體構件:是抽象構件的實現,通常裝飾的就是這玩意component
(3)裝飾角色:通常是一個抽象類,也繼承了抽象構件,通常會有一個私有方法依賴抽象構件對象
(4)具體裝飾角色:繼承裝飾角色,對具體構件進行裝飾,或者對裝飾角色進行裝飾繼承