设计模式装饰器模式
概念理解:我早上需要吃早饭,今天吃鸡蛋,明天喝牛奶,在吃鸡蛋+ 牛奶,如果用简单的代码实现,关鸡蛋+牛奶,两种情况,我需要枚举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();
}
}
第一天想吃每天早上都要吃饭
吃鸡蛋
第二天想吃
每天早上都要吃饭
吃鸡蛋
喝牛奶
如果我在想加其他食物,只需要增加装饰类
类图借鉴
以上是 设计模式装饰器模式 的全部内容, 来源链接: utcz.com/z/517307.html