Java 设计模式—装饰者模式
在Java编程语言中,嵌套了非常多设计模式的思想,比如IO流中的缓冲流就使用到以下要介绍的装饰者设计模式。
演示样例代码:
* 抽象构件角色:定义一个抽象接口,来规范准备附加功能的类 * @author Admin * */ public interface Drink { //被装饰者的基类 public String description(); public int price(); }
/** * 详细构件角色:将要被附加功能的类,实现抽象构件角色接口 * @author Admin * */ public class SoyaBeanMilk implements Drink{ //被装饰者的详细类 public String description() { return "豆浆"; } public int price() { return 2; } }
/** * 抽象装饰者角色:持有对详细构件角色的引用(被装饰者)并实现抽象构件角色一致的接口 * @author Admin * */ public class Decorator implements Drink{ //装饰者的基类 private Drink drink; public Decorator(Drink drink) { this.drink = drink; } public String description() { return drink.description(); } public int price() { return drink.price(); } }
/** * 详细装饰角色:实现抽象装饰者角色。负责为详细构件加入额外功能. * @author Admin * */ public class Sugar extends Decorator{ //装饰者详细类 public Sugar(Drink drink) { super(drink); } public String description() { return super.description()+" 糖"; } public int price() { return super.price()+1; } } /** * 详细装饰角色:实现抽象装饰者角色,负责为详细构件加入额外功能. * @author Admin * */ public class BlackBean extends Decorator{ public BlackBean(Drink drink) { super(drink); } public String description() { return super.description()+" 黑豆"; } public int price() { return super.price()+3; } }
/** * 測试类(測试装饰者模式) * @author Admin * */ public class Test { public static void main(String[] args) { Drink drink = new SoyaBeanMilk(); //被装饰者(豆浆) System.out.println(drink.description()+"花费:"+drink.price()); Drink drink1 = new Sugar(drink); //糖是装饰者类。用来装饰豆浆 System.out.println(drink1.description()+"花费:"+drink1.price()); Drink drink2 = new BlackBean(drink); //用黑豆来装饰豆浆 System.out.println(drink2.description()+"花费:"+drink2.price()); Drink drink3 = new BlackBean(drink1); //用黑豆来装饰糖豆浆 System.out.println(drink3.description()+"花费:"+drink3.price()); } }
实验结果: