装饰器详解及案例分析

装饰器模式

装饰器模式也叫包装模式,是指在不改变原有对象的基础上,将功能附加到对象上,提供比集成更有弹性的替代方案。属于结构型模式

适用场景

  • 用于扩展一个类的功能或给一个类添加附加职责
  • 动态的给一个对象添加功能,这些功能可以在动态的撤销

案例

public interface Component {

    void operation();
}

public class ConcreteComponent implements Component {
    public ConcreteComponent() {
        System.out.println("创建具体构件角色");
    }

    @Override
    public void operation() {
        System.out.println("调用具体构件角色的方法operation()");
    }
}

public class ConcreteDecorator extends Decorator {

    public ConcreteDecorator(Component component) {
        super(component);
    }

    @Override
    public void operation() {
        super.operation();
        addedFunction();
    }

    public void addedFunction() {
        System.out.println("为具体构件角色增加额外的功能addedFunction()");
    }
}

public abstract class Decorator implements  Component {
    private Component component;

    public Decorator(Component component) {
        this.component = component;
    }

    @Override
    public void operation() {
        component.operation();
    }
}

public class Test {

    public static void main(String[] args) {
        ConcreteComponent concreteComponent = new ConcreteComponent();
        ConcreteDecorator concreteDecorator = new ConcreteDecorator(concreteComponent);
        concreteDecorator.operation();
    }
}

// 输出
创建具体构件角色
调用具体构件角色的方法operation()
为具体构件角色增加额外的功能addedFunction()

装饰器模式的优点

  • 采用装饰模式扩展对象的功能比采用继承方式更加灵活。
  • 可以设计出多个不同的具体装饰类,创造出多个不同行为的组合。

装饰器模式的缺点

  • 装饰模式增加了许多子类,如果过度使用会使程序变得很复杂。

源码中的装饰器模式

java.io中的InputStream/OutputStream

InputStream fileInputStream = new FileInputStream(new File("demo.txt"));
InputStream bin = new BufferedInputStream(fileInputStream);
DataInputStream din = new DataInputStream(bin);
int data = din.readInt();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

猿道apeto

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值