设计模式之【装饰者--Decorator】
2015-07-24 17:01
507 查看
1、接口
2、接口实现类--被装饰者
3、装饰类
4、实现扩展
5、结果
装饰器模式的应用场景:
1、需要扩展一个类的功能。
2、动态的为一个对象增加功能,而且还能动态撤销。(继承不能做到这一点,继承的功能是静态的,不能动态增删。)
缺点:产生过多相似的对象,不易排错!
package Decorator; public interface Sourceable { public void method(); }
2、接口实现类--被装饰者
package Decorator; public class Source implements Sourceable{ @Override public void method() { // TODO Auto-generated method stub System.out.println("接口原始方法的实现"); } }
3、装饰类
package Decorator; //装饰类,在原有类的基础上通过接口添加新方法 public class Decorator implements Sourceable{ private Sourceable source; public Decorator(Sourceable source){ super(); //调用父类构造方法 this.source = source; } @Override public void method() { // TODO Auto-generated method stub System.out.println("装饰前"); source.method(); System.out.println("装饰后"); } }
4、实现扩展
package Decorator; public class DecoratorTest { public static void main(String[] args) { // TODO Auto-generated method stub Sourceable source = new Source(); Sourceable obj = new Decorator(source); obj.method(); } }
5、结果
装饰前 接口原始方法的实现 装饰后
装饰器模式的应用场景:
1、需要扩展一个类的功能。
2、动态的为一个对象增加功能,而且还能动态撤销。(继承不能做到这一点,继承的功能是静态的,不能动态增删。)
缺点:产生过多相似的对象,不易排错!
相关文章推荐
- RHEL九(分析和存储日志)
- springMVC工作原理
- maven update project
- 简单的 iOS 表格
- android开发-简单动画2
- Effective Go(官方文档)笔记
- android dialog使用详情
- Web开发中的乱码问题
- 单例模式 - GCD 、兼容ARC和MRC
- 【LeetCode 29】Divide Two Integers
- C# FileSystemWatcher 在监控文件夹和文件时的用法
- 日志文件锁定问题
- MATLAB常用1
- 百度云推送ios没收到信息怎么破
- php database search
- 计算两段yuv格式视频流中每一帧的psnr值
- 日志文件锁定问题
- hdu1879 继续畅通工程(最小生成树)
- 024.KVO 键值监听
- 腐蚀与膨胀