装饰器(Decorator)模式跟适配器(Adapter)模式一样,属于构建型设计模式。在学习适配器模式的时候说过,适配器模式的重点在复用能力,装饰器模式的重点在扩展能力。换言之,装饰器模式是先复用后扩展,这也导致了很多人跟适配器模式混淆。装饰器模式意在实现了相同接口的类,在不继承的情况下,实现组件的功能扩展。多内聚,少继承。例子是从网上摘录下来的:
- interface Sourcable {
- public void operation();
- }
- class Source implements Sourcable {
- public void operation() {
- System.out.println("原始类的方法");
- }
- class Decorator1 implements Sourcable {
- private Sourcable sourcable;
- public Decorator1(Sourcable sourcable){
- super();
- this.sourcable=sourcable;
- }
- public void operation() {
- System.out.println("第一个装饰器前");
- sourcable.operation();
- System.out.println("第一个装饰器后");
- }
- }
- class Decorator2 implements Sourcable {
- private Sourcable sourcable;
- public Decorator2(Sourcable sourcable){
- super();
- this.sourcable=sourcable;
- }
- public void operation() {
- System.out.println("第二个装饰器前");
- sourcable.operation();
- System.out.println("第二个装饰器后");
- }
- }
- class Decorator3 implements Sourcable {
- private Sourcable sourcable;
- public Decorator3(Sourcable sourcable){
- super();
- this.sourcable=sourcable;
- }
- public void operation() {
- System.out.println("第三个装饰器前");
- sourcable.operation();
- System.out.println("第三个装饰器后");
- }
- }
- public class Test {
- /**
- * @param args
- */
- public static void main(String[] args) {
- Sourcable source = new Source();
- // 装饰类对象
- Sourcable obj = new Decorator1(new Decorator2(new Decorator3(source)));
- obj.operation();
- }
- }
运行该程序的输出如下:
第一个装饰器前
第二个装饰器前
第三个装饰器前
原始类的方法
第三个装饰器后
第二个装饰器后
第一个装饰器后
一层层装饰,相互之间解耦,如果new的时候换一种顺序,结果又是一种情况,这就是装饰器的巧妙之处。看懂了这个,那么java中的io包的装饰器模式就能了然。装饰器模式是除了继承之外,另一种扩展功能的办法。
参考资料:http://blog.csdn.net/vincentzhao2009/article/details/6201928