利用场景

装璜器模式次要解决继承关系过于简单的问题,通过组合来代替继承。它次要的作用是给原始类增加加强性能。

装璜器模式有一个特点,那就是能够对原始类嵌套应用多个装璜器。为了满足这个利用场景,在设计的时候,装璜器类须要跟原始类继承雷同的抽象类或者接口。

聊聊Java IO类

Java IO 类库十分宏大和简单,有几十个类,负责 IO 数据的读取和写入。咱们能够把IO类分为四类。

字节流字符流
输出流InputStreamReader
输入流OutputStreamWriter

针对不同的读取和写入场景,Java IO 又在这四个父类根底之上,扩大出了很多子类。

置信大多数开发者在首次接触Java IO类时面对宏大的Java IO类家族产生困惑:为什么会有如此多的类?他们应用上有啥区别?

这里以读取 config.properties 文件为例,InputStream 是一个抽象类,FileInputStream 是专门用来读取文件流的子类。BufferedInputStream 是一个反对带缓存性能的数据读取类,能够进步数据读取的效率。

InputStream in = new FileInputStream("config.properties");InputStream bin = new BufferedInputStream(in);byte[] data = new byte[128];while (bin.read(data) != -1) {  //...}

Java IO 为什么不设计一个继承 FileInputStream 并且反对缓存的BufferedFileInputStream 类呢?这样咱们就能够间接创立new BufferedFileInputStream() 简略许多。

继承的问题

事实上如果只是扩大这一个类,那还能够承受,然而InputStream具备很多子类,如果咱们持续依照继承的形式来实现的话,就须要再持续派生出 DataFileInputStream、DataPipedInputStream 等类。如果咱们还须要既反对缓存、又反对依照根本类型读取数据的类,那就要再持续派生出 BufferedDataFileInputStream、BufferedDataPipedInputStream 等 n 多类。这还只是附加了两个加强性能,如果咱们须要附加更多的加强性能,那就会导致组合爆炸,类继承构造变得无比简单,代码既不好扩大,也不好保护。

所以Java的设计者没有应用继承的形式来进行扩大,而是应用组合,这里也体现了组合优于继承的设计准则。上面是简化的JDK源码

public abstract class InputStream {    // ...}public class BufferedInputStream extends InputStream {      protected volatile InputStream in;        public BufferedInputStream(InputStream in) {        this.in = in;    }            // 实现基于缓存的读取...}public class DataInputStream extends InputStream {      protected volatile InputStream in;        public BufferedInputStream(InputStream in) {        this.in = in;    }            // 实现读取根本数据类型...}

如果去查看 JDK 的源码,你会发现,BufferedInputStream、DataInputStream 并非继承自 InputStream,而是另外一个叫 FilterInputStream 的类。

这是因为InputStream是一个抽象类,其中很多办法曾经有了默认实现。咱们想复用这些实现,然而咱们是通过在构造函数注入InputStream,而后赋值给成员变量InputStream in,将所有性能委托给成员变量in来实现的,因而抽象类InputStream的办法即便被继承,调用的对象也是以后类实例,而不是委托给in,所以须要有一个装璜器类FilterInputStream

public class FilterInputStream extends InputStream {  protected volatile InputStream in;  protected FilterInputStream(InputStream in) {    this.in = in;  }  public int read() throws IOException {    return in.read();  }  public int read(byte b[]) throws IOException {    return read(b, 0, b.length);  }     public int read(byte b[], int off, int len) throws IOException {    return in.read(b, off, len);  }  public long skip(long n) throws IOException {    return in.skip(n);  }  public int available() throws IOException {    return in.available();  }  public void close() throws IOException {    in.close();  }  public synchronized void mark(int readlimit) {    in.mark(readlimit);  }  public synchronized void reset() throws IOException {    in.reset();  }  public boolean markSupported() {    return in.markSupported();  }}

装璜器模式是简略的“用组合代替继承”吗?

当然不是。从 Java IO 的设计来看,装璜器模式有两个比拟非凡的中央:

  • 装璜器类和原始类继承同样的父类,这样咱们能够对原始类“嵌套”多个装璜器类。
InputStream in = new FileInputStream("content.txt");InputStream bin = new BufferedInputStream(in);DataInputStream din = new DataInputStream(bin);int data = din.readInt();
  • 装璜器类是对性能的加强,这也是装璜器模式利用场景的一个重要特点。

跟代理模式的区别

代理模式中,代理类附加的是跟原始类无关的性能,而在装璜器模式中,装璜器类附加的是跟原始类相干的加强性能。

类图

代码实现

Shape

public abstract class Shape {    public abstract void draw();    public abstract void doOther();}

Circle

public class Circle extends Shape {    @Override    public void draw() {        System.out.println("You are drawing circle...");    }    @Override    public void doOther() {        System.out.println("You are doing other...");    }}

Square

public class Square extends Shape {    @Override    public void draw() {        System.out.println("You are drawing square...");    }    @Override    public void doOther() {        System.out.println("You are doing other...");    }}

ShapeDecorator

public class ShapeDecorator extends Shape {    protected Shape shape;    public ShapeDecorator(Shape shape) {        this.shape = shape;    }    @Override    public void draw() {        shape.draw();    }    @Override    public void doOther() {        shape.doOther();    }}

RedShapeDecorator

public class RedShapeDecorator extends ShapeDecorator {    public RedShapeDecorator(Shape shape) {        super(shape);    }    @Override    public void draw() {        shape.draw();        System.out.println("The shape color is red");    }}

Main

public class Main {    public static void main(String[] args) {        Shape shape;        RedShapeDecorator decorator;        shape = new Circle();        decorator = new RedShapeDecorator(shape);        decorator.draw();        decorator.doOther();        shape = new Square();        decorator = new RedShapeDecorator(shape);        decorator.draw();        decorator.doOther();    }}