用装饰者模式前:
代码如下:
package com.yuan;
/**
* @author QLBF
* @version 1.0
* @date 2021/6/4 20:58
*/
//1.快餐抽象类(抽象构件(Component)角色)
abstract class FastFood{
private float price;
//描述
private String desc;
//定义获取价格的抽象方法,因为要统计金额,不能写死,所以要抽象
public abstract float cost();
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;
}
}
//2.1炒饭(具体构件(Concrete Component)角色)
class FriedRice extends FastFood{
public FriedRice(){
super(10,"炒饭");
}
@Override
public float cost() {
return getPrice();
}
}
//2.2炒面
class FriedNoodles extends FastFood{
public FriedNoodles(){
super(12,"炒面");
}
@Override
public float cost() {
return getPrice();
}
}
//3.配料类(装饰者类,重点,也要为抽象类)
abstract class Garnish extends FastFood{
//还要把它加进来,关键
private FastFood fastFood;
public FastFood getFastFood() {
return fastFood;
}
public void setFastFood(FastFood fastFood) {
this.fastFood = fastFood;
}
public Garnish(FastFood fastFood, float price, String desc) {
super(price, desc);
this.fastFood = fastFood;
}
}
//4.1鸡蛋配料(具体装饰(ConcreteDecorator)角色 )
class Egg extends Garnish{
public Egg(FastFood fastFood) {
super(fastFood,1,"鸡蛋");
}
@Override
public float cost() {
return getPrice()+getFastFood().getPrice();
}
@Override
public String getDesc() {
return super.getDesc()+getFastFood().getDesc();
}
}
//4.2培根配料(具体装饰(ConcreteDecorator)角色 )
class Bacon extends Garnish{
public Bacon(FastFood fastFood) {
super(fastFood,2,"培根");
}
@Override
public float cost() {
return getPrice()+getFastFood().getPrice();
}
@Override
public String getDesc() {
return super.getDesc()+getFastFood().getDesc();
}
}
//测试类
public class decorateClient {
public static void main(String[] args) {
//点一份炒饭
FastFood food=new FriedRice();
//花费的价格
System.out.println(food.getDesc() + " " + food.cost() + "元");
System.out.println("========");
//点一份加鸡蛋的炒饭
FastFood food1=new FriedRice();
food1=new Egg(food1);
//花费的价格
System.out.println(food1.getDesc() + " " + food1.cost() + "元");
System.out.println("========");
//点一份加培根的炒面
FastFood food2=new FriedNoodles();
food2=new Bacon(food2);
//花费的价格
System.out.println(food2.getDesc() + " " + food2.cost() + "元");
}
}
想加主食和配菜都随便扩展了
来源:黑马