码迷,mamicode.com
首页 > 其他好文 > 详细

[工作中的设计模式]装饰模式decorator

时间:2016-02-16 23:24:13      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:

一、模式解析

 装饰模式又名包装(Wrapper)模式。装饰模式以对客户端透明的方式扩展对象的功能,是继承关系的一个替代方案。

装饰模式的要点主要是:

1、需要对已有对象扩展新的功能,又不希望改变原有对象接口;

2、装饰者对象与原有对象需要继承相同接口,初始化装饰对象时将原有对象传入装饰对象;

3、可以对一个对象定义多个装饰着对象,进行分别装饰或者组合装饰

技术分享

二、模式代码

1、抽象接口

package decorator.patten;

public interface Component {
    public void operation();
}

2、定义被装饰对象

package decorator.patten;

public class ConcreteComponent implements Component {

    @Override
    public void operation() {
        System.out.println("我是被装饰对象,我执行了");
    }

}

3、定义装饰者对象A

package decorator.patten;

public class DecoratorA implements Component {
    Component component;
    public DecoratorA(Component component){
        this.component=component;
    }
    @Override
    public void operation() {
        System.out.println("我是装饰对象A,我在被装饰对象前增加打印");
        component.operation();
    }

}

4、定义装饰者对象B

package decorator.patten;

public class DecoratorB implements Component {
    Component component;
    public DecoratorB(Component component){
        this.component=component;
    }
    @Override
    public void operation() {
        component.operation();
        System.out.println("我是装饰对象b,我在被装饰对象后添加打印");
    }

}

5、定义客户端

public class Client {
    public static void main(String[] args) {
        Component component=new DecoratorB(new DecoratorA(new ConcreteComponent()));
        component.operation();
    }
}

6、执行结果

我是装饰对象A,我在被装饰对象前增加打印
我是被装饰对象,我执行了
我是装饰对象b,我在被装饰对象后添加打印

三、说明

1、装饰着模式可以为被装饰者添加新的功能,,将核心功能和装饰功能进行分离,比如日志打印,字符集处理等
2、可以对对象进行多此装饰,装饰均会被执行
3、示例中多次装饰没有顺序,但实际中往往会是有序的,比如数据加密和数据过滤,如果先加密再过滤就会出现问题
4、装饰对象和被装饰对象均集成同一个接口,有时候为了简化,我们会将装饰对象直接集成被装饰对象,这就是子类重写父类方法达到扩展功能的
四、应用场景

装饰模式最典型的应用就是java IO中对inputstream和outputstream的装饰,例如

dis = new DataInputStream(
                    new BufferedInputStream(
                            new FileInputStream("test.txt")
                    )
            );

 

[工作中的设计模式]装饰模式decorator

标签:

原文地址:http://www.cnblogs.com/jyyzzjl/p/5194023.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!