裝飾器模式 容許向一個現有的對象添加新的功能,同時又不改變其結構。裝飾者能夠在所委託被裝飾者的行爲以前或以後加上本身的行爲,以達到特定的目的。java
裝飾器模式由組件和裝飾者組成。設計模式
抽象組件(Component):須要裝飾的抽象對象。
具體組件(ConcreteComponent):是咱們須要裝飾的對象
抽象裝飾類(Decorator):內含指向抽象組件的引用及裝飾者共有的方法。
具體裝飾類(ConcreteDecorator):被裝飾的對象。markdown
假設咱們如今去咖啡店要了一杯咖啡,能夠加奶、加糖等等。咖啡和奶、糖分別有不一樣的價格。
咖啡就是咱們的組件,奶和糖是咱們的裝飾者,如今咱們要計算調製這樣一杯咖啡花費多少。ide
Drink 接口類:post
package DesignPattern.Strategy.Decorator; public interface Drink { public float cost(); public String getDescription(); }
Coffee 類:測試
package DesignPattern.Strategy.Decorator; public class Coffee implements Drink { final private String description = "coffee"; //每杯 coffee 售價 10 元 public float cost() { return 10; } public String getDescription() { return description; } }
CondimentDecorator 調味抽象類:this
package DesignPattern.Strategy.Decorator; public abstract class CondimentDecorator implements Drink { protected Drink decoratorDrink; public CondimentDecorator(Drink decoratorDrink) { this.decoratorDrink = decoratorDrink; } public float cost() { return decoratorDrink.cost(); } public String getDescription() { return decoratorDrink.getDescription(); } }
Milk 牛奶裝飾類:spa
package DesignPattern.Strategy.Decorator; public class Milk extends CondimentDecorator { public Milk(Drink decoratorDrink) { super(decoratorDrink); } @Override public float cost() { return super.cost() + 2; } @Override public String getDescription() { return super.getDescription() + " milk"; } }
Sugar 裝飾類:設計
package DesignPattern.Strategy.Decorator; public class Sugar extends CondimentDecorator { public Sugar(Drink decoratorDrink) { super(decoratorDrink); } @Override public float cost() { return super.cost() + 1; } @Override public String getDescription() { return super.getDescription() + " sugar"; } }
測試代碼:code
package DesignPattern.Strategy.Decorator; public class CoffeeShop { public static void main(String[] args) { //點一杯coffee Drink drink = new Coffee(); System.out.println(drink.getDescription() + ":" + drink.cost()); //加一份奶 drink = new Milk(drink); System.out.println(drink.getDescription() + ":" + drink.cost()); //加一份糖 drink = new Sugar(drink); System.out.println(drink.getDescription() + ":" + drink.cost()); //再加一份糖 drink = new Sugar(drink); System.out.println(drink.getDescription() + ":" + drink.cost()); } }
上圖咱們能夠看出 coffee 加不一樣的調味料價格的不一樣。
參考:
Head First 設計模式