抽象构件
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());
}
}
类图

【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix