裝飾器模式 - Decorator Pattern
- 裝飾器模式(Decorator Pattern)允許向一個現(xiàn)有的對象添加新的功能,同時又不改變其結(jié)構(gòu)。這種類型的設(shè)計模式屬于結(jié)構(gòu)型模式,它是作為現(xiàn)有的類的一個包裝。
-
意圖: 動態(tài)地給一個對象添加一些額外的職責(zé)披摄。就增加功能來說馆铁,裝飾器模式相比生成子類更為靈活
- 這種模式創(chuàng)建了一個裝飾類跑揉,用來包裝原有的類,并在保持類方法簽名完整性的前提下埠巨,提供了額外的功能历谍。
目前有一個現(xiàn)有的業(yè)務(wù)邏輯 并 有實現(xiàn)邏輯
public interface ProductLevel {
void createProduct();
}
public class LowProductLevel implements ProductLevel {
@Override
public void createProduct() {
System.out.println("默認(rèn)創(chuàng)建一個低等級的項目");
}
}
定義一個裝飾器
public class LowProductLevelDecorator implements ProductLevel {
private ProductLevel productLevel;
public LowProductLevelDecorator(ProductLevel productLevel) {
this.productLevel = productLevel;
}
@Override
public void createProduct() {
productLevel.createProduct();
}
public void createHighProduct() {
// 調(diào)用原有默認(rèn)的邏輯
productLevel.createProduct();
// 裝飾更多的邏輯
System.out.println("添加創(chuàng)建的這個低等級的項目的說明");
}
}
使用這個裝飾器
public static void main(String[] args) {
new LowProductLevelDecorator(new LowProductLevel()).createHighProduct();
}
輸出
默認(rèn)創(chuàng)建一個低等級的項目
添加創(chuàng)建的這個低等級的項目的說明