抽象构件
public abstract class FastFood {
public String desc;
public int price;
public abstract String getDesc();
public abstract int getPrice();
}
具体构件
米饭
public class Rice extends FastFood {
public Rice() {
this.desc = "米饭";
this.price = 10;
}
@Override
public String getDesc() {
return this.desc;
}
@Override
public int getPrice() {
return this.price;
}
}
面条
public class Noddle extends FastFood {
public Noddle() {
this.desc = "面条";
this.price = 8;
}
@Override
public String getDesc() {
return this.desc;
}
@Override
public int getPrice() {
return this.price;
}
}
抽象装饰器
public abstract class SideFood extends FastFood {
FastFood fastFood;
public SideFood(FastFood fd) {
this.fastFood = fd;
}
@Override
public String getDesc() {
return this.fastFood.getDesc();
}
@Override
public int getPrice() {
return this.fastFood.getPrice();
}
}
具体装饰器
鸡蛋
public class Egg extends SideFood {
public Egg(FastFood fd) {
super(fd);
}
@Override
public String getDesc() {
return this.fastFood.getDesc() + "加鸡蛋";
}
@Override
public int getPrice() {
return this.fastFood.getPrice() + 5;
}
}
火腿
public class Ham extends SideFood {
public Ham(FastFood fd) {
super(fd);
}
@Override
public String getDesc() {
return this.fastFood.getDesc() + "加火腿";
}
@Override
public int getPrice() {
return this.fastFood.getPrice() + 8;
}
}
使用案例
public class Main {
public static void main(String[] args) {
Rice rice = new Rice();
Egg egg = new Egg(rice);
Ham ham = new Ham(egg);
System.out.println(ham.getDesc());
System.out.println(ham.getPrice());
}
}