欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

设计模式(四)--装饰器模式

程序员文章站 2022-05-04 19:34:12
...

装饰器模式:动态的将责任附加到对象上,若要扩展功能,装饰者提供了比继承更有弹性的替代方案。

 

意图:将一个接口转换为另一个接口 

 

设计原则:开闭原则(对类的扩展开放,对修改关闭)

 

装饰器模式设计要点:

1.装饰者和被装饰对象有相同的超类型

2.可以用一个或者多个装饰者去包装一个对象

3.装饰者可以在所委托被装饰者的行为之前或者之后,加上自己的行为,已达到特定的目的

 

/**
 * Created by Administrator on 2017/12/10.
 * 饮料类
 */
public abstract class Beverage {
    protected String desc;
    public String getDesc(){
        return desc;
    }
    protected abstract double cost();
}

 

 

/**
 * Created by Administrator on 2017/12/10.
 * 调料装饰器
 */
public abstract class CondimentDecorator  extends Beverage{
    public abstract String getDesc();
}

 

/**
 * Created by Administrator on 2017/12/10.
 *HouseBlend coffee
 */
public class HouseBlend extends Beverage {
    public HouseBlend() {
        desc = "houseBlend";
    }

    @Override
    protected double cost() {
        return 10;
    }
}

 

/**
 * Created by Administrator on 2017/12/10.
 * 用Mocha去装饰饮料
 */
public class Mocha extends CondimentDecorator {
    private Beverage beverage;

    public Mocha(Beverage beverage) {
        this.beverage = beverage;
    }

    @Override
    public String getDesc() {
        return beverage.getDesc() + " Mocha ";
    }

    @Override
    protected double cost() {
        //可以在这里做一些事情
        double price = 6;
        price = beverage.cost() + price;
        return price;
    }
}

 

/**
 * Created by Administrator on 2017/12/10.
 */
public class TestDecorator {
    public static void main(String[] args) {
        Beverage beverage = new HouseBlend();
        beverage = new Mocha(beverage); //用mocha去装饰coffee
        System.out.println(beverage.cost() + "," + beverage.getDesc());
        beverage = new Mocha(beverage); //两次用Mocha去装饰coffee
        System.out.println(beverage.cost() + "," + beverage.getDesc());
    }
}