
装饰者模式
发布日期:2021-05-08 20:26:19
浏览次数:20
分类:精选文章
本文共 2181 字,大约阅读时间需要 7 分钟。
装饰者模式
装饰者模式——动态地将责任附加到对象上。想要扩展功能,装饰者提供了比继承更有弹性的替代方案。
以买手抓饼为例子
抽象原料类------Material
package decorator5;public abstract class Material { String desc; Double price; public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } public abstract double price();}
原味饼-------Pie
package decorator5;public class Pie extends Material{ public Pie(){ setDesc("原味手抓饼噢噢5.0"); setPrice(5.0); } @Override public double price() { return 5.0; }}
紫薯味的饼------PurplePie
package decorator5;public class PurplePie extends Material{ public PurplePie(){ setDesc("紫薯手抓饼嗷5.5"); setPrice(5.5); } @Override public double price() { return getPrice(); }}
装饰者的类------Decorator
package decorator5;public abstract class Decorator extends Material{ private Material material; public Decorator(Material material){ this.material = material; } @Override public String getDesc(){ return desc + price +"&" + material.getDesc(); } @Override public double price(){ return price + material.price(); }}
鸡蛋类------Egg
package decorator5;public class Egg extends Decorator{ public Egg(Material material) { super(material); setDesc("土鸡蛋"); setPrice(1.5); }}
热狗类-------HotDog
package decorator5;public class HotDog extends Decorator{ public HotDog(Material material) { super(material); setDesc("热狗啊"); setPrice(2.5); }}
测试------Client
package decorator5;public class Client { public static void main(String[] args) { Material order = new Pie(); order = new Egg(order); System.out.println("订单的描述为:"+ order.getDesc()); System.out.println("订单的总价钱为:" + order.price()); System.out.println("====================="); order = new HotDog(order); System.out.println("订单的描述为:"+ order.getDesc()); System.out.println("订单的总价钱为:" + order.price()); }}
发表评论
最新留言
能坚持,总会有不一样的收获!
[***.219.124.196]2025年04月08日 05时26分07秒
关于作者

喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
使用JWT作为Spring Security OAuth2的token存储
2019-03-06
使用Redis作为Spring Security OAuth2的token存储
2019-03-06
【SOLVED】Linux使用sudo到出现输入密码提示延迟时间长
2019-03-06
项目引入非配置的文件,打成war包后测试报错的可能原因
2019-03-06
Git学习笔记
2019-03-06
SpringBoot笔记
2019-03-06
让你的代码更优秀的 14 条建议
2019-03-06
不需要爬虫也能轻松获取 unsplash 上的图片
2019-03-06
将博客搬至CSDN
2019-03-06
elementUi源码解析(1)--项目结构篇
2019-03-06
自动遍历测试之Monkey工具
2019-03-06
Nmap扫描工具介绍
2019-03-06
算法笔记:递归、动态规划
2019-03-06
Pytest插件开发
2019-03-06
常用Windows 快捷键
2019-03-06