作用: 擴充項物件的功能。
涉及角色:
1 、抽象構件角色:定義一個抽象介面,來規範準備附加功能的類。
2 、具體構件角色:將要被附加功能的類,實現抽象構件角色介面。
3 、抽象裝飾者角色:持有對具體構件角色的引用並定義與抽象構件角色一致的介面。
4、具體裝飾角色:實現抽象裝飾者角色,負責為具體構件添加額外功能。
代碼執行個體:
抽象構件角色java 代碼
package decorator;
public interface InterfaceComponent {
public void say();
}
具體構件角色java 代碼
package decorator;
public class Component implements InterfaceComponent{
public void say() {
System.out.println("Component.say():原組件的方法!");
}
}
抽象裝飾者角色java 代碼
package decorator;
public abstract class AbstractDecorator implements InterfaceComponent{
private InterfaceComponent component;
public AbstractDecorator(InterfaceComponent component){
this.component = component;
}
protected void preSay(){}; //組件方法執行前預先處理方法
protected void afterSay(){}; //組件方法執行後處理方法
public void say(){
preSay();
component.say();
afterSay();
};
}
具體裝飾者二java 代碼
package decorator;
public class DecoratorTwo extends AbstractDecorator{
public DecoratorTwo(InterfaceComponent component) {
super(component);
}
protected void preSay(){ //根據需要重載模板類preSay()方法
System.out.println("DecoratorTwo.preSay():裝飾者二的preSay()方法!");
}
protected void afterSay(){ //根據需要重載模板類afterSay()方法
System.out.println("DecoratorTwo.afterSay():裝飾者二的afterSay()方法!");
}
}
裝飾者一java 代碼
package decorator;
public class DecoratorOne extends AbstractDecorator{
public DecoratorOne(InterfaceComponent component) {
super(component);
}
protected void preSay(){ //根據需要重載模板類preSay()方法
System.out.println("DecoratorOne.preSay():裝飾者一的preSay()方法!");
}
protected void afterSay(){ //根據需要重載模板類afterSay()方法
System.out.println("DecoratorOne.afterSay():裝飾者一的afterSay()方法!");
}
public static void main(String[] args) { // 測試方法
InterfaceComponent interfaceComponent = new DecoratorTwo(new DecoratorOne(new Component()));
interfaceComponent.say();
}
}
控制台輸出:
-
* 控制台輸出:
-
* DecoratorTwo.preSay():裝飾者二的preSay()方法!
-
* DecoratorOne.preSay():裝飾者一的preSay()方法!
-
* Component.say():原組件的方法!
-
* DecoratorOne.afterSay():裝飾者一的afterSay()方法!
-
* DecoratorTwo.afterSay():裝飾者二的afterSay()方法!
4、優缺點
優點:1)提供比繼承更多的靈活性 2)使用不同的裝飾組合可以創造出不同行為的組合 3)需要的類的數目減少
缺點:1)靈活性帶來比較大的出錯性 2)產生更多的對象,給查錯帶來困難