一、概念ide
裝飾模式動態地給一個對象添加一些額外的職責。就擴展功能而言,它比生成子類方式更爲靈活,屬於結構性模式一種。
二、模式結構this
三、使用場景調試
四、優缺點code
優勢:cdn
缺點:對象
五、實例繼承
在購買奶茶的時候,常常會有選擇配料的選項,每種配料的價格不同,能夠多種組合,價格也不同。首先先定義奶茶的接口,具備名稱和價格方法接口
public interface IMilkTea { String name(); double price(); }
繼承IMilkTea的相關茶類class
public class RedTea implements IMilkTea { @Override public String name() { return "紅茶"; } @Override public double price() { return 10; } }
public class GreenTea implements IMilkTea { @Override public String name() { return "綠茶"; } @Override public double price() { return 12; } }
定義具體裝飾類Decorator,裝飾相關奶茶
public class Decorator implements IMilkTea { @Override public String name() { return null; } @Override public double price() { return 0; } }
繼承Decorator的相關類
public class IceCream extends Decorator { private String name = "加雪糕"; private IMilkTea milkTea; public IceCream(IMilkTea milkTea) { this.milkTea = milkTea; } @Override public String name() { return milkTea.name() + name; } @Override public double price() { return milkTea.price() + 3; } }
public class Pearl extends Decorator { private String name = "加珍珠"; private IMilkTea milkTea; public Pearl(IMilkTea milkTea) { this.milkTea = milkTea; } @Override public String name() { return milkTea.name() + name; } @Override public double price() { return milkTea.price() + 2; } }
客戶端使用
public static void main(String[] args) { IMilkTea milkTea = new RedTea(); milkTea = new IceCream(milkTea); milkTea = new Pearl(milkTea); System.out.println(milkTea.name() + "\n價格:" + milkTea.price()); }