设计模式(9)------装饰模式
来源:互联网 发布:sqlserver导出csv文件 编辑:程序博客网 时间:2024/05/21 07:03
装饰模式作用:
动态的给对象添加一些额外的职责。
应用场景:
(1) 在不影响其他对象的情况下,以动态,透明的方式给单个对象添加职责。
(2) 处理可以撤销的职责。
(3) 当不能采用子类的方法进行扩充时。
参与对象:
(1)Component
定义一个接口,准备接收动态添加的职责。
(2)ConcreteComponent
实现接口,将要接受添加职责的对象类。
(3)Decorator
持有一个构件(Component)对象的实例,并定义一个与抽象构件接口一致的接口。
(4)ConcreteDecorator
负责给构件对象添加上附加的责任
eg:
Component
package com.lanhuigu.base.design.construct.decorator;/** * Component: 定义一个接口,准备接收动态添加的职责 */public interface Person {void eat();}
ConcreteComponent
package com.lanhuigu.base.design.construct.decorator;/** * ConcreteComponent: 实现接口,将要接受添加职责的对象类 */public class Man implements Person {@Overridepublic void eat() {// TODO Auto-generated method stubSystem.out.println("男人吃完饭");}}
Decorator
package com.lanhuigu.base.design.construct.decorator;/** * Decorator: 持有一个构件(Component)对象的实例,并定义一个与抽象构件接口一致的接口 */public abstract class Decorator implements Person {protected Person person;public Person getPerson() {return person;}public void setPerson(Person person) {this.person = person;}@Overridepublic void eat() {// TODO Auto-generated method stubperson.eat();}}
ConcreteDecorator
package com.lanhuigu.base.design.construct.decorator;/** * ConcreteDecorator: 负责给构件对象添加上附加的责任 */public class ManDecoratorOne extends Decorator{public void eat() {super.eat();smoking();System.out.println("======第一类抽烟男人饭后所为======");}private void smoking() {// TODO Auto-generated method stubSystem.out.println("饭后一支烟,赛过活神仙");}}
package com.lanhuigu.base.design.construct.decorator;/** * ConcreteDecorator: 负责给构件对象添加上附加的责任 */public class ManDecoratorTwo extends Decorator{public void eat() {super.eat();noSmoking();System.out.println("======第二类不抽烟男人饭后所为======");}private void noSmoking() {// TODO Auto-generated method stubSystem.out.println("饭后不抽烟,没事使牙签");}}
Test
package com.lanhuigu.base.design.construct.decorator;public class Test {public static void main(String[] args) {Man man = new Man();ManDecoratorOne oneMan = new ManDecoratorOne();ManDecoratorTwo twoMan = new ManDecoratorTwo();oneMan.setPerson(man);twoMan.setPerson(man);oneMan.eat();twoMan.eat();}}
运行结果
总结
在oneMan和twoMan吃饭的基础上分别动态添加了抽烟和剔牙的职责
0 0
- 设计模式:9)装饰者模式
- 设计模式(9)------装饰模式
- 设计模式(9)-装饰模式
- 设计模式(9)--装饰模式
- golang设计模式(9)装饰模式
- 设计模式(装饰设计模式)
- 设计模式(装饰设计模式)
- 设计模式---装饰模式
- 设计模式:装饰模式
- 设计模式------装饰模式
- 设计模式--装饰模式
- 设计模式--装饰模式
- 设计模式--装饰模式
- 设计模式 装饰模式
- 设计模式----装饰模式
- 设计模式-【装饰模式】
- 设计模式--装饰模式
- 设计模式装饰模式
- 设计模式(8)------组合模式
- MySQL重命名表(RENAME TABLE语句)
- 什么是OSGI
- hive--计算方差标准差
- 如何取div中包含的span的value
- 设计模式(9)------装饰模式
- QVBoxLayout移除控件之后没有消失
- cmd命令行下查看utf8的编码文件
- MySQL重命名表(RENAME TABLE语句)
- Android绘制一条宽度逐渐变大的路径
- sql优化
- 设计模式(10)------外观模式
- Revit开发之设置剖面框
- Java中throw和throws的区别