设计模式-装饰模式(Decorator)
来源:互联网 发布:mac磁盘分区失败 编辑:程序博客网 时间:2024/06/10 19:24
装饰模式又名包装(Wrapper)模式
装饰模式以对客户端透明的方式扩展对象的功能,是继承关系的一个替代方案
装饰模式以对客户透明的方式动态的给一个对象附加上更多的责任
装饰模式的角色:
- 抽象构件角色(Component):给出一个抽象接口,以规范准备接受附加责任的对象。例如inputStream…
- 具体构件角色(Concrete Component): 定义一个将要接受附加责任的类。例如节点流(FileInputStream)…
- 装饰角色(Decorator):持有一个构件(Component)对象的引用,并定义一个与抽象构件接口一致的接口。例如过滤流的顶层类(FilterInputStream)
- 具体装饰角色(Concrete Decorator):负责给构件对象“贴上”附加的责任。例如过滤流的具体实现(BufferedInputStream)…
实现的场景:
1.Java中I/O流的实现
具体实现:
componet:
public interface Component { public void doSomething();}
Concrete Component:
public class ConcreteComponent implements Component { @Override public void doSomething() { System.out.println("具体功能直接实现"); }}
decorator:
public class Decorator implements Component { private Component component; public Decorator(Component component){ this.component = component; } @Override public void doSomething() { component.doSomething(); }}
concrete decorator:
public class ConcreteDecorator1 extends Decorator { public ConcreteDecorator1(Component component) { super(component); } @Override public void doSomething() { super.doSomething(); this.doAnotherThing(); } private void doAnotherThing() { System.out.println("功能A"); }}
client:
public class Client { public static void main(String[] args) { Component component = new ConcreteDecorarot2(new ConcreteDecorator1(new ConcreteComponent())); component.doSomething(); }}
返回结果:
具体功能直接实现
功能A
功能B
可以进行debug追踪执行过程,先进入到ConcreteDecorarot2执行doSomething,然后执行父类Decorator中的doSomething,该方法会执行传入的component中的doSomething也就是传入的ConcreteDecorarot1,ConcreteDecorarot1的执行最后也会执行到传入进来的component的doSomething,也就是最里面的ConcreteComponent的doSomething,然后从里往外返回出去。
阅读全文
0 0
- 设计模式 - 装饰 Decorator
- Decorator(装饰)设计模式
- 设计模式-装饰模式(Decorator Pattern)
- 设计模式---装饰模式(decorator)
- 设计模式 (十)装饰模式(Decorator)
- 设计模式 (十)装饰模式(Decorator)
- 设计模式 (十)装饰模式(Decorator)
- 【设计模式】之装饰模式(Decorator)
- 设计模式之装饰模式(Decorator)
- 设计模式之 装饰模式(Decorator)
- 设计模式之装饰模式(Decorator)
- Java设计模式---装饰模式(Decorator)
- 设计模式(五):装饰模式(Decorator)
- 设计模式(7)--Decorator 装饰模式
- 设计模式:装饰模式(Decorator)
- 设计模式之装饰(Decorator)模式
- 设计模式:装饰模式(Decorator )
- 设计模式:装饰模式(Decorator)
- CVPR2017 all paper list
- 2012-2013 ACM-ICPC, Asia Tokyo Regional Contest F.Never Wait for Weights(带权并查集模板)
- STL学习之五:stack用法示例
- cocos creator将智能提示加入到webstorm中
- 柱面坐标变换
- 设计模式-装饰模式(Decorator)
- 七大查找算法
- hdu 5889 最短路+裸最小割
- 集群基础----(高可用+负载均衡)
- python出现undefined variable from import 的错误
- [1] UI原型设计工具Pencil Project 学习系列----- 为什么选择
- 设计模式-单例模式,工厂模式
- Excel 技巧百例:数值的阶梯性计算
- hdu 2017 字符串统计