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

本文详细介绍了装饰模式的概念及其应用。装饰模式允许在不修改原始类的情况下为其添加新功能,通过组合不同的装饰类可以灵活地扩展对象的行为。文章还提供了具体的代码实现示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、模式解析

 装饰模式又名包装(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")
                    )
            );

 

转载于:https://www.cnblogs.com/jyyzzjl/p/5194023.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值