设计模式详解之装饰模式
2013-03-15 16:33
190 查看
装饰模式(Decorator):顾名思义,装饰模式就是给一个对象增加一些新的功能,而且是动态的,要求装饰对象和被装饰对象实现同一个接口,装饰对象持有被装饰对象的实例,关系图如下:
Source类是被装饰类,Decorator类是一个装饰类,可以为Source类动态的添加一些功能,代码如下:
public interface Sourceable {
public void method();
}
测试类:
public class DecoratorTest {
public static void main(String[] args) {
Sourceable source = new Source();
Sourceable obj = new Decorator(source);
obj.method();
}
}
输出:
before decorator!
the original method!
after decorator!
装饰器模式的应用场景:
1、需要扩展一个类的功能。
2、动态的为一个对象增加功能,而且还能动态撤销。(继承不能做到这一点,继承的功能是静态的,不能动态增删。)
缺点:产生过多相似的对象,不易排错!
Source类是被装饰类,Decorator类是一个装饰类,可以为Source类动态的添加一些功能,代码如下:
public interface Sourceable {
public void method();
}
public class Source implements Sourceable { @Override public void method() { System.out.println("the original method!"); } }
public class Decorator implements Sourceable { private Sourceable source; public Decorator(Sourceable source){ super(); this.source = source; } @Override public void method() { System.out.println("before decorator!"); source.method(); System.out.println("after decorator!"); } }
测试类:
public class DecoratorTest {
public static void main(String[] args) {
Sourceable source = new Source();
Sourceable obj = new Decorator(source);
obj.method();
}
}
输出:
before decorator!
the original method!
after decorator!
装饰器模式的应用场景:
1、需要扩展一个类的功能。
2、动态的为一个对象增加功能,而且还能动态撤销。(继承不能做到这一点,继承的功能是静态的,不能动态增删。)
缺点:产生过多相似的对象,不易排错!
相关文章推荐
- Java 装饰器模式详解
- 设计模式系列-装饰模式 推荐
- 设计模式(二)之装饰器模式
- 设计模式(三):装饰模式
- JAVAWEB开发之Servlet Filter(过滤器)详解包括post和get编码过滤器、URL访问权限控制、自动登录。以及装饰模式的使用
- 设计模式(3)--装饰模式
- 设计模式之装饰(Decorator)模式 代码详解
- PHP面向对象程序设计组合模式与装饰模式详解
- 设计模式C++实现(11)——装饰模式
- (十)装饰器模式详解(与IO不解的情缘)
- Java设计模式之装饰模式原理与用法实例详解
- (十)装饰器模式详解(与IO不解的情缘)
- (十)装饰器模式详解(与IO不解的情缘)
- 设计模式(五):装饰模式(Decorator)
- 设计模式(11)-策略模式详解(易懂)
- 设计模式系列之-装饰模式
- PHP设计模式之装饰器模式实例详解
- (十)装饰器模式详解(与IO不解的情缘)
- 设计模式(9)装饰模式--结构型