设计模式(2)装饰器模式
装饰模式实例
public class Decorator {
public static void main(String[] args) {
Food food1 = new DanChaofan();
Food food2 = new KaoRouFan();
food1 = new JiaJiTui(food1);
food1 = new JiaShaoFan(food1);
food2 = new JiaShaoFan(food2);
System.out.println(food1.name() + "--" + food1.price());
System.out.println(food2.name() + "--" + food2.price());
}
}
//通用接口
interface Food {
String name();
Double price();
}
//被装饰实现类 蛋炒饭
class DanChaofan implements Food {
public String name() {
return "蛋炒饭";
}
public Double price() {
return 15.00;
}
}
//被装饰实现类 烤肉饭
class KaoRouFan implements Food {
public String name() {
return "烤肉饭";
}
public Double price() {
return 18.00;
}
}
//抽象装饰类
abstract class JiaNiao implements Food {
Food food;
public JiaNiao(Food food) {
this.food = food;
}
}
//具体装饰类 加个鸡腿
class JiaJiTui extends JiaNiao {
JiaJiTui(Food food) {
super(food);
}
public String name() {
return food.name() + " 加个鸡腿";
}
public Double price() {
return food.price() + 5;
}
}
//具体装饰类 加份饭
class JiaShaoFan extends JiaNiao {
JiaShaoFan(Food food) {
super(food);
}
public String name() {
return food.name() + " 加份饭";
}
public Double price() {
return food.price() + 2;
}
}
借用现代化的流水化生产线来类比,一条流水线是由多个不同的操作部门来组成的,比如一辆车,要经过上色,喷漆,烤漆一系列流程,当现在的流水线是生产红色的车,若要生产黑色的车,需要重新建一条流水线么,很显然,只用把上色操作部门切换成上黑色而已。或者说现在我想要在车上加个图案,同样的仅仅需要在流水线的合适位置加上对应的作画部门而已。所谓装饰模式就是避免了过多的新建流水线的一种策略。