作用:在不修改對象外觀和功能的情況下添加或者刪除對象功能,即給一個對象動態(tài)附加職能
裝飾器模式主要包含以下角色。
- 抽象構件(Component)角色:定義一個抽象接口以規(guī)范準備接收附加責任的對象。
- 具體構件(ConcreteComponent)角色:實現(xiàn)抽象構件,通過裝飾角色為其添加一些職責。
- 抽象裝飾(Decorator)角色:繼承抽象構件,并包含具體構件的實例,可以通過其子類擴展具體構件的功能。
- 具體裝飾(ConcreteDecorator)角色:實現(xiàn)抽象裝飾的相關方法,并給具體構件對象添加附加的責任。
文章來源:http://www.zghlxwxcb.cn/news/detail-836921.html
package decorator;
public class DecoratorPattern {
public static void main(String[] args) {
Component p = new ConcreteComponent();
p.operation();
System.out.println("---------------------------------");
Component d = new ConcreteDecorator(p);
d.operation();
}
}
//抽象構件角色
interface Component {
public void operation();
}
//具體構件角色
class ConcreteComponent implements Component {
public ConcreteComponent() {
System.out.println("創(chuàng)建具體構件角色");
}
public void operation() {
System.out.println("調(diào)用具體構件角色的方法operation()");
}
}
//抽象裝飾角色
class Decorator implements Component {
private Component component;
public Decorator(Component component) {
this.component = component;
}
public void operation() {
component.operation();
}
}
//具體裝飾角色
class ConcreteDecorator extends Decorator {
public ConcreteDecorator(Component component) {
super(component);
}
public void operation() {
super.operation();
addedFunction();
}
public void addedFunction() {
System.out.println("為具體構件角色增加額外的功能addedFunction()");
}
}
運行結果文章來源地址http://www.zghlxwxcb.cn/news/detail-836921.html
創(chuàng)建具體構件角色
調(diào)用具體構件角色的方法operation()
---------------------------------
調(diào)用具體構件角色的方法operation()
為具體構件角色增加額外的功能addedFunction()
到了這里,關于【設計模式】01-裝飾器模式Decorator的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!