裝飾(Decorator)模式又名包裝(Wrapper)模式。裝飾模式以對客戶端透明的方式擴展對象的功能,是繼承關系的一個替代方案。
一,結構
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
抽象構件(Component)角色: 給出一個抽象接口,以規范準備接收附加責任的對象。
具體構件(Concrete Component)角色: 定義一個將要接收附加責任的類。
裝飾(Decorator)角色: 持有一個構件(Component)對象的實例,并定義一個與抽象構件接口一致的接口。
具體裝飾(Concrete Decorator)角色: 負責給構件對象"貼上"附加的責任。
二,示例代碼
/**
* 抽象構件
* @author Salmon
*
*/
public interface Component {
public void operation();
}
/**
* 具體構件
* @author Salmon
*
*/
public class ConcreteComponent implements Component {
public void operation() {
System.out.println("ConcreteComponent.Operation()");
}
}
/**
* 裝飾(即組合又繼承)
* @author Salmon
*
*/
public class Decorator implements Component {
protected Component component;
public void setComponent(Component component) {
this.component = component;
}
public void operation() {
if (component != null)
component.operation();
}
}
/**
* 具體裝飾
* @author Salmon
*
*/
public class ConcreteDecoratorA extends Decorator {
private String addedState;
public void operation() {
super.operation();
addedState = "new state";
System.out.println("ConcreteDecoratorA.Operation()");
}
}
/**
* 具體裝飾
* @author Salmon
*
*/
public class ConcreteDecoratorB extends Decorator {
public void operation() {
super.operation();
AddedBehavior();
System.out.println("ConcreteDecoratorB.Operation()");
}
private void AddedBehavior() {
System.out.println("new state");
}
}
/**
* 客戶代碼
* @author Salmon
*
*/
public class Client {
public static void main(String[] args) {
ConcreteComponent c = new ConcreteComponent();
ConcreteDecoratorA d1 = new ConcreteDecoratorA();
ConcreteDecoratorB d2 = new ConcreteDecoratorB();
d1.setComponent(c);
d2.setComponent(d1);
d2.operation();
}
}
?
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

