架构说明
构成简述:
总接口:
装饰者跟被装饰者都要来实现他(或者理解成父接口),作用:对被装饰者做转换
被装饰者:
此处实现总接口。什么都不需要动,他只是被增强的功能!
装饰者:
装饰者负责定义共有功能
具体装饰者:
实现具体的功能
具体代码:
总接口:
public interface ICoffee {
void makeCoffee();
}
被装饰者:
public class OriginalCoffee implements ICoffee {
public OriginalCoffee() {
System.out.println("原味咖啡调用无参构造创建自己,来自OriginalCoffee");
}
@Override
public void makeCoffee() {
System.out.println("原味咖啡 ");
}
}
装饰者(抽象)
public class CoffeeDecorator implements ICoffee{
private ICoffee coffee;
public CoffeeDecorator() {
System.out.println("CoffeeDecorator无参构造被调用,来自CoffeeDecorator");
}
public CoffeeDecorator(ICoffee iCoffee) {
System.out.println("CoffeeDecorator有参构造被调用,来自CoffeeDecorator");
this.coffee = iCoffee;
}
@Override
public void makeCoffee() {
coffee.makeCoffee();
}
}
具体装饰者
public class MilkDecorator extends CoffeeDecorator{
public MilkDecorator() {
System.out.println("MilkDecorator无参构造被调用来自MilkDecorator");
}
public MilkDecorator(ICoffee iCoffee) {
super(iCoffee);
}
@Override
public void makeCoffee() {
super.makeCoffee();
addMilk();
}
private void addMilk(){
System.out.println("加奶 ");
}
}
客户端
public class Client {
public static void main(String[] args) {
//执行结果
//原味咖啡
//
//原味咖啡
//加奶
//
//原味咖啡
//加奶
//加糖
//原味咖啡(1)
ICoffee coffee=new OriginalCoffee();
coffee.makeCoffee(); //原味咖啡
System.out.println("");
//加奶的咖啡(1)
coffee=new MilkDecorator(coffee);
coffee.makeCoffee(); //原味咖啡 加奶
System.out.println("");
//先加奶后加糖的咖啡(1)
coffee=new SugarDecorator(coffee);
coffee.makeCoffee(); //原味咖啡 加奶 加糖
System.out.println("");
//跟上面的:原味咖啡(1)相等
new OriginalCoffee().makeCoffee();
//跟上面的:加奶的咖啡(1)相等
new MilkDecorator(new OriginalCoffee()).makeCoffee();
//跟上面的:先加奶后加糖的咖啡(1)相等
new SugarDecorator(new MilkDecorator(new OriginalCoffee())).makeCoffee();
}
}
调用链路(核心思想)
我学习所看的文章
https://zhuanlan.zhihu.com/p/64584677