装饰器设计模式–快餐店案例
某快餐店提供粉、面等各种快餐,顾客购买时可要求添加其它食物,例如加鸡蛋、加豆腐干、加猪脚等等,快餐店需计算快餐的总价,请用装饰器设计模式解决该问题。
快餐店提供的各种食品抽象为一个抽象类–foods
//抽象构件
public abstract class foods {
//获取要计算的商品的名称
public abstract String getName();
//计算价格
public abstract double calculate();
//打印名称:价格
public abstract void displayPrice();
//打印商品描述 包括加了什么
public abstract String getDescription();
}
具体构件–快餐店具体提供的食品
public class BeefNoodles extends foods {
private String name = "牛肉面";
private double price = 10;
public String getName() {
return name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public double calculate() {
return this.price;
}
@Override
public void displayPrice() {
System.out.println((this.name + " : " + this.calculate()));
}
@Override
public String getDescription() {
return this.name;
}
}
装饰角色–需有一个私有的变量指向抽象构件
//抽象装饰者
public abstract class Decorator extends foods{
private foods noodle = null;
//构造函数传递被装饰者
public Decorator(foods noodle){
this.noodle = noodle;
}
@Override
public String getName(){
return this.noodle.getName();
}
@Override
public double calculate(){
return this.noodle.calculate();
}
@Override
public void displayPrice(){
this.noodle.displayPrice();
}
@Override
public String getDescription(){
return this.noodle.getDescription();
}
}
装饰器的具体实现
public class AddEgg extends Decorator {
//定义被修饰者
private String addname = "鸡蛋";
private double EggPrice = 0.5;
public AddEgg(foods noodle) {
super(noodle);
}
private double addegg()
{
return this.EggPrice;
// System.out.println("这里加了一个鸡蛋");
}
@Override
public double calculate() {
return super.calculate() + this.addegg();
}
@Override
public void displayPrice(){
System.out.println(( this.getName() + " : " + this.calculate()));
}
@Override
public String getName(){
return super.getName();
}
@Override
public String getDescription(){
return super.getDescription() + " + " + this.addname;
}
}
测试方法
public class testmain {
public static void main(String[] args) {
//买一碗牛肉面
foods noodle = new BeefNoodles();
// noodle.displayPrice();
//加鸡蛋 0.5
noodle = new AddEgg(noodle);
// noodle.displayPrice();
//再加一个豆腐干 1.5
noodle = new AddToufu(noodle);
// noodle.displayPrice();
//加上猪脚 12
noodle = new AddPigFeet(noodle);
noodle.displayPrice();
System.out.println(noodle.getDescription());
//桂林米粉加鸡蛋 加 猪脚
foods ricenoodles = new AddPigFeet(new AddEgg(new Vermicelli()));
ricenoodles.displayPrice();
System.out.println(ricenoodles.getDescription());
}
}