装饰者模式(Decorator、Compoment)(早餐销售装饰,动态添加职责)

适用于以下情况:

(1)需要扩展一个类的功能,或给一个类添加附加职责。

(2)需要动态的给·一个对象添加功能,这些功能可以再动态的撤销。

(3)需要增加由一些基本功能的排列组合而产生的非常大量的功能,从而使继承关系变得不现实。

(4)当不能采用生成子类的方法进行扩充时,一种情况是:可能有大量独立的扩展,为支持每一种组合将产生大量的子类,使得子类数目爆炸性增长,另一种情况可能是因为类定义被隐藏,或定义不能用于生成子类。

(设计者模式能提供更多的灵活性,创造出更多不同行为的组合)

(设计者模式会导致,设计中出现许多小类,如果过度使用,会是程序变得很复杂)

(装饰者模式是针对抽象组件类型编程,但是如果要是针对具体组件编程,就应该重新思考应用架构,以及装饰者是否合适)

抽象构件类:

 1 public abstract class Breskfast {
 2 private String desciption = "未知";
 3 public String getDesciption() {
 4     return desciption;
 5 }
 6 public void setDesciption(String desciption) {
 7     this.desciption = desciption;
 8 }
 9 public abstract double cost();
10 }

抽象装饰类:

 1 public abstract class CondimentDecorator extends Breskfast{
 2 private Breskfast myfood;
 3 
 4 public Breskfast getMyfood() {
 5     return myfood;
 6 }
 7 public CondimentDecorator(Breskfast myfood) {
 8     super();
 9     this.myfood = myfood;
10 }
11 
12 @Override
13     public String getDesciption() {
14         return myfood.getDesciption();
15 
16     }
17     @Override
18     public double cost() {
19         return myfood.cost();
20     }
21 
22 }

具体构件类:

 1 public class Toast extends Breskfast{
 2 public Toast() {
 3     this.setDesciption("吐司");
 4 }
 5 
 6 @Override
 7 public double cost() {
 8     return 10;
 9 }
10 
11 }

具体装饰类:

 1 public class Ham extends CondimentDecorator{
 2 
 3     public Ham(Breskfast myfood) {
 4         super(myfood);
 5     }
 6 
 7     @Override
 8     public double cost() {
 9         return super.cost()+10;
10     }
11     @Override
12     public String getDesciption() {
13         return super.getDesciption()+",火腿";
14     }
15     
16 }

客户测试类:

 1 public class Decorator {
 2 
 3     public static void main(String[] args) {
 4         //点一份吐司
 5       Breskfast breskfast = new Toast();
 6       System.out.println(breskfast.getDesciption()+"价格为:"+breskfast.cost());
 7       //加两份火腿
 8      breskfast = new Ham(breskfast);
 9      breskfast = new Ham(breskfast);
10     // System.out.println(breskfast.desciption);
11      System.out.println(breskfast.getDesciption()+"价格为:"+breskfast.cost());
12     }
13 
14 }
原文地址:https://www.cnblogs.com/the-wang/p/7273530.html