总共有培根类、鸡蛋类、炒面类、炒饭类。两个抽象类 抽象快餐类、装饰器类继承抽象快餐类
炒面类继承快餐类
/**
* @author Dsmash
*/
public class FriedNoodles extends FastFood{
public FriedNoodles(){
super(10,"炒面");
}
@Override
public float cost() {
return getPrice();
}
}
炒饭类继承快餐类
public class FriedRice extends FastFood{
public FriedRice(){
super(13,"炒饭");
}
@Override
public float cost() {
return getPrice();
}
}
快餐类
public abstract class FastFood {
private float price;
private String desc;
public FastFood() {
}
public FastFood(float price, String desc) {
this.price = price;
this.desc = desc;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public abstract float cost();
}
培根类装饰快餐,继承装饰者类
public class Bacon extends Garnish{
@Override
public float cost() {
return getPrice() + getFastFood().cost();
}
public Bacon(FastFood fastFood){
super(fastFood,2,"培根");
}
@Override
public String getDesc() {
return super.getDesc()+getFastFood().getDesc();
}
}
鸡蛋类继承装饰者类
public class Egg extends Garnish{
@Override
public float cost() {
return getPrice()+ getFastFood().cost();
}
public Egg(FastFood fastFood){
super(fastFood,1,"鸡蛋");
}
@Override
public String getDesc() {
return super.getDesc()+getFastFood().getDesc();
}
}
装饰者类测试
@Test
public void testDecoratorAddEgg(){
FastFood food=new FriedRice();
System.out.println(food.getDesc()+" "+food.cost()+"元");
food=new Egg(food);//加个鸡蛋
System.out.println(food.getDesc()+" "+food.cost()+"元");
food=new Bacon(food);//再加个培根
System.out.println(food.getDesc()+" "+food.cost()+"元");
}