装饰设计模式
来源:互联网 发布:淘宝店铺刷信誉 编辑:程序博客网 时间:2024/05/19 20:19
装饰模式是为了已有功能动态的添加到对象上,它把每个要装饰的功能放在单独的类中,并让这个类包装它所要装饰的对象,以此需要执行特殊行为的时候,客户代码就可以在运行的时候有选择的,按顺序使用装饰类包装对象了。
定义:动态给一个对象添加一些额外的职责,就象在墙上刷油漆.使用Decorator模式相比用生成子类方式达到功能的扩充显得更为灵活。
装饰模式的UML图如下
现在就举个案例使用一下装饰模式
//定义一个对象接口interface FoodComponent{public void process();public void setPrice();}
//具体被装饰对象class malatang implements FoodComponent{public void process() {System.out.println("麻辣烫已经煮好了");}public void setPrice() {System.out.println("麻辣烫的价格为1元");}}
//装饰抽象类,继承HumanComponent,从外部来扩展HumanComponent类的功能abstract class Decorator implements FoodComponent{FoodComponent food;Decorator(FoodComponent food){this.food =food;}public void process() {food.process();}public void setPrice() {food.setPrice();}}class Decorator_one extends Decorator{Decorator_one(FoodComponent humn) {super(humn);}public void process() {super.process();System.out.println("麻辣烫加点辣椒");}public void setPrice() {super.setPrice();}} class Decorator_two extends Decorator{Decorator_two(FoodComponent humn) {super(humn);}public void process() {super.process();System.out.println("麻辣烫加点香菜");}public void setPrice() {System.out.println("麻辣烫价格涨到2元啦");}}
客户端代码
public static void main(String[] args) { FoodComponent food = new malatang(); // food.process(); //food.setPrice(); Decorator_one one = new Decorator_one(food); // one.process(); // one.setPrice(); Decorator_two two =new Decorator_two(one); two.process(); two.setPrice(); }
0 0
- 设计模式---装饰模式
- 设计模式:装饰模式
- 设计模式------装饰模式
- 设计模式--装饰模式
- 设计模式--装饰模式
- 设计模式--装饰模式
- 设计模式 装饰模式
- 设计模式----装饰模式
- 设计模式-【装饰模式】
- 设计模式--装饰模式
- 设计模式装饰模式
- 设计模式 - 装饰模式
- 设计模式-----装饰模式.
- 设计模式-----装饰模式.
- [ 设计模式 ] 装饰模式!
- 设计模式:装饰模式
- 设计模式 - 装饰模式
- 设计模式 - 装饰模式
- IOS文件的管理
- VRMMO的技术挑战
- Linux中SIGPIPE信号说明
- 深入研究Servlet线程安全性问题
- HTTP协议分析系列(六)------php+socket+cookie请求
- 装饰设计模式
- activeMQ在文件上传的应用
- VueJS2 todoList Demo
- Kafka集群搭建
- 音频焦点的基本用法
- 小程眼里的微服务
- Zookeeper + HBase 安装(详细图文)
- 每位架构师都应该熟知的 10 个 SOA 设计模式
- HTTP协议分析系列(七)------http协议之refer防盗链