是一种结构型设计模型,允许在不改变对象结构的情况下,动态的将新的功能添加到对象上,
通过组合而非继承的方式来实现功能的扩展。他可以在运行时动态的添加活移除对象的功能,而无需修改原始对象的代码。
继承关系过于复杂的问题,通过组合来代替继承。
用于扩展一个类的功能,或者给一个类添加附加职责
动态的给一个对象添加功能,这些功能可以动态的被撤销
需要为一批平行的兄弟类进行改造或者加装功能
咖啡接口
package Decorator;
/**
* 抽象咖啡类
*/
public interface Coffee {
double getCost();
String getDescription();
}
装饰器抽象类
package Decorator;
/**
* 装饰器抽象类
*/
public abstract class CoffeeDecorator implements Coffee {
//静态代理
/**
* 静态代理:
* 创建目标 创建代理对象 将目标传给代理对象
*/
protected final Coffee decoratorCoffee;
public CoffeeDecorator(Coffee decoratorCoffee) {
this.decoratorCoffee = decoratorCoffee;
}
@Override
public double getCost() {
return decoratorCoffee.getCost();
}
@Override
public String getDescription() {
return decoratorCoffee.getDescription();
}
}
普通咖啡类:
package Decorator;
/**
* 基础咖啡类
*/
public class SimpleCoffee implements Coffee{
@Override
public double getCost() {
return 1.0;
}
@Override
public String getDescription() {
return "Simple coffee";
}
}
牛奶装饰器类
package Decorator;
/**
* 牛奶装饰器
*/
public class MilkDecorator extends CoffeeDecorator {
public MilkDecorator(Coffee decoratorCoffee) {
super(decoratorCoffee);
}
@Override
public double getCost() {
return super.getCost() + 0.5;
}
@Override
public String getDescription() {
return super.getDescription() + "with milk";
}
}
糖浆装饰器类
package Decorator;
/**
* 糖浆装饰器
*/
public class SyrupDecorator extends CoffeeDecorator{
public SyrupDecorator(Coffee decoratorCoffee) {
super(decoratorCoffee);
}
@Override
public double getCost() {
return super.getCost() + 1;
}
@Override
public String getDescription() {
return super.getDescription() + "with 糖浆";
}
}
测试类:
package Decorator;
public class Client {
public static void main(String[] args) {
//基本咖啡
Coffee simpleCoffee = new SimpleCoffee();
System.out.println("simpleCoffee" + simpleCoffee.getDescription() + ",cost:" + simpleCoffee.getCost());
//咖啡 + 牛奶
Coffee milkCoffee = new MilkDecorator(simpleCoffee);
System.out.println("milkCoffee:" + milkCoffee.getDescription() + ",cost:" + milkCoffee.getCost());
//咖啡 + 牛奶 + 糖
Coffee syrupCoffee = new SyrupDecorator(milkCoffee);
System.out.println("syrupCoffee + milkCoffee:" + syrupCoffee.getDescription() + ",cost:" + syrupCoffee.getCost());
}
}
项目地址: https://gitee.com/htzGittee/design-patterns/tree/master/designPatterns