概念理解:我早上需要吃早饭,今天吃鸡蛋,明天喝牛奶,在吃鸡蛋+ 牛奶,如果用简单的代码实现,关鸡蛋+牛奶,两种情况,我需要枚举3个场景,如果需要的东西叠加,枚举也跟着递增,所以产生了装饰器模式。先来看代码,在来理解概念
定义接口
//吃饭, 定义了全部的组件接口
public interface EatFoodComponen {
public void eatFood();
}
接口的具体实现、
//具体的吃饭行为,需要被装饰器装饰的原始类
public class EatFoodConcreteComponent implements EatFoodComponen {
@Override
public void eatFood() {
System.out.println("每天早上都要吃饭");
}
}
装饰类
//装饰器
public class Egg implements EatFoodComponen {
private EatFoodComponen eatFoodComponen;
public Egg(EatFoodComponen eatFoodComponen) {
this.eatFoodComponen = eatFoodComponen;
}
@Override
public void eatFood() {
eatFoodComponen.eatFood();
System.out.println("吃鸡蛋");
}
}
public class Milk implements EatFoodComponen {
private EatFoodComponen eatFoodComponen;
public Milk(EatFoodComponen eatFoodComponen) {
this.eatFoodComponen = eatFoodComponen;
}
@Override
public void eatFood() {
eatFoodComponen.eatFood();
System.out.println("喝牛奶");
}
}
测试类
public class Clinet {
public static void main(String[] args) {
EatFoodComponen componen = new EatFoodConcreteComponent();
System.out.println("第一天想吃");
EatFoodComponen myCom = new Egg(componen);
myCom.eatFood();
System.out.println("第二天想吃");
myCom = new Milk(new Egg(componen));
myCom.eatFood();
}
}
第一天想吃
每天早上都要吃饭
吃鸡蛋
第二天想吃
每天早上都要吃饭
吃鸡蛋
喝牛奶
如果我在想加其他食物,只需要增加装饰类
类图借鉴
来源:oschina
链接:https://my.oschina.net/u/3900969/blog/4307143