成子类方式达到功能的扩充显得更为灵活.
Decorator可以动态的拓展功能,而避免了继承太多带来的系统种类繁杂导致类爆炸,可以由用户动态的决定加入的方式和时机,即插即用。
我分成6个类:一个主类,一个接口,一个实现类,一个抽象类作装饰模式的装饰类Decorator(核心)实现接口,还有两个是装饰类。
为了更加的生动形象,我把手抓饼作为例子,饼是接口,原味手抓饼是实现类,然后装饰类就是加牛扒和鸡蛋。
主类(测试类):
package 装饰模式; public class Test { public static void main(String[] args) { CrasphingCake cc = new CrasphingCake(); Beef bef = new Beef(cc); bef.fire(); bef.description(); bef.price(); System.out.println(bef.description()); System.out.println(bef.price()); System.out.println(bef.fire()); } }
package 装饰模式; public interface Cake { public float price();//获取价格 public String description();//描述 }
package 装饰模式; public class CrasphingCake implements Cake{ public float price() { return 3.0f; } public String description() { return "原味手抓饼"; } }
package 装饰模式; public abstract class Decorator implements Cake{ //装饰类强关联Cake private Cake cake; public Decorator(Cake cake){ this.cake = cake; } public float price() { return cake.price(); } public String description() { return cake.description(); } }
package 装饰模式; public class Egg extends Decorator{ public Egg(Cake cake) { super(cake); } public float price(){ return super.price()+1.5f; } public String description(){ return super.description()+"+鸡蛋"; } }
package 装饰模式; public class Beef extends Decorator{ public Beef(Cake cake) { super(cake); } public float price(){ return super.price()+2.0f; } public String description(){ return super.description()+"+牛扒"; } public String fire(){ return "牛排需要三分熟"; } }
装饰模式可以动态的为对象添加拓展功能,避免了因继承太多出现类爆炸的现象。