结构型模式之装饰模式

装饰模式Decorator,也可称为包装器Wrapper。相比于用继承的方式扩展功能,装饰模式用更少的类对功能灵活组合。
(Adapter和Decorator均可称为包装器Wrapper,但Adapter是包装接口,Decorator是包装具体对象)


装饰模式包含以下四部分:

  • Component 被装饰者接口
  • ConcreteComponent 具体的被装饰者类
  • Decorator 装饰者接口,与Component接口一致,持有Component对象的引用
  • ConcreteDecorator 具体装饰者类

Java I/O类库中的filter(过滤器)类,即使用了装饰器模式。
FilterInputStream和FilterOutputStream这两个基类提供了装饰器类的接口,用于控制InputStream和OutputStream的特定输入、输出流。

Component 被装饰者接口

public abstract class InputStream implements Closeable {
    public abstract int read() throws IOException;
}

ConcreteComponent 具体的被装饰者类

public class FileInputStream extends InputStream {

}

Decorator 装饰者接口

public class FilterInputStream extends InputStream {
    /**
     * The input stream to be filtered.
     */
    protected volatile InputStream in;

    public int read() throws IOException {
        return in.read();
    }
}

ConcreteDecorator 具体装饰者类

public class BufferedInputStream extends FilterInputStream {

}

public class DataInputStream extends FilterInputStream implements DataInput {

}

用例

public void decoratorDemo () throws FileNotFoundException {
        InputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream("fileName")));
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值