插: AI時代,程序員或多或少要了解些人工智能,前些天發現了一個巨牛的人工智能學習網站,通俗易懂,風趣幽默,忍不住分享一下給大家(前言 – 人工智能教程 )
堅持不懈,越努力越幸運,大家一起學習鴨~~~
裝飾者設計模式(Decorator Pattern)是一種結構型設計模式,允許你動態地將新行為添加到對象實例中。這種模式通過創建一個包裝類,也就是裝飾者,來包裹原始的類,并在不改變其接口的情況下,增加新的功能。在Java中,裝飾者模式廣泛應用于需要擴展對象功能或動態地為對象添加功能的場景。
裝飾者模式的基本結構
在裝飾者模式中,通常有四個角色:
-
Component(組件接口):定義一個對象接口,可以動態地給這些對象添加職責。
-
ConcreteComponent(具體組件):實現Component接口的具體對象,是被裝飾的原始對象。
-
Decorator(裝飾者抽象類):實現Component接口,并持有一個Component對象引用。這個類可以為Component對象動態添加功能。
-
ConcreteDecorator(具體裝飾者):擴展Decorator類的功能,具體實現裝飾功能。
示例:在Java中實現一個簡單的裝飾者模式
假設我們有一個基礎的咖啡接口和具體的咖啡實現類,然后我們想要為這些咖啡添加額外的調料(裝飾者),比如牛奶或者糖漿。
Step 1: 定義組件接口
// Component 接口
public interface Coffee {String getDescription();double getCost();
}
Step 2: 創建具體組件類
// ConcreteComponent 具體咖啡類
public class SimpleCoffee implements Coffee {@Overridepublic String getDescription() {return "Simple Coffee";}@Overridepublic double getCost() {return 1.0;}
}
Step 3: 定義裝飾者抽象類
// Decorator 裝飾者抽象類
public abstract class CoffeeDecorator implements Coffee {protected Coffee decoratedCoffee;public CoffeeDecorator(Coffee coffee) {this.decoratedCoffee = coffee;}public String getDescription() {return decoratedCoffee.getDescription();}public double getCost() {return decoratedCoffee.getCost();}
}
Step 4: 創建具體裝飾者類
// ConcreteDecorator 具體裝飾者類 - 牛奶
public class MilkDecorator extends CoffeeDecorator {public MilkDecorator(Coffee coffee) {super(coffee);}@Overridepublic String getDescription() {return super.getDescription() + ", with Milk";}@Overridepublic double getCost() {return super.getCost() + 0.5;}
}
Step 5: 使用裝飾者模式
public class DecoratorPatternExample {public static void main(String[] args) {// 創建基礎咖啡Coffee coffee = new SimpleCoffee();System.out.println("Cost: " + coffee.getCost() + "; Description: " + coffee.getDescription());// 加牛奶coffee = new MilkDecorator(coffee);System.out.println("Cost: " + coffee.getCost() + "; Description: " + coffee.getDescription());// 加糖漿coffee = new SyrupDecorator(coffee);System.out.println("Cost: " + coffee.getCost() + "; Description: " + coffee.getDescription());}
}
解釋說明:
-
SimpleCoffee 實現了 Coffee 接口,表示基礎的咖啡。
-
CoffeeDecorator 是裝飾者的抽象類,持有一個 Coffee 對象的引用,通過組合的方式擴展 Coffee 的功能。
-
MilkDecorator 和 SyrupDecorator 分別是具體的裝飾者類,通過繼承 CoffeeDecorator 并重寫相關方法,實現對咖啡的裝飾。
通過這種方式,我們可以動態地為咖啡添加不同的調料,而不需要修改原始的咖啡類。這種設計模式提供了靈活性和可擴展性,使得我們可以在運行時動態地添加功能,而不會影響到其他對象。
裝飾者模式在Java中的應用不僅局限于咖啡例子,還可以用于文件流處理、UI組件的動態功能添加等各種場景,是一種非常有用的設計模式。