大厂是怎么实践装饰器模式的()

厌伴老儒烹瓠叶,强随举子踏槐花。这篇文章主要讲述大厂是怎么实践装饰器模式的?相关的知识,希望能为你提供帮助。
1 简介一般有两种方式给一个类或对象新增行为:

  • 继承 子类在拥有自身方法同时还拥有父类方法。但这种是静态的,用户无法控制增加行为的方式和时机
  • 关联 将一个类的对象嵌入另一个对象,由另一个对象决定是否调用嵌入对象的行为以便扩展自身行为,这个嵌入的对象就叫做装饰器(Decorator)
2 定义结构型模式。
动态给一个对象增加额外功能,装饰器模式比生成子类实现更为灵活。装饰模式以对用户透明的方式动态给一个对象附加功能。用户不会觉得对象在装饰前、后有何不同。装饰模式可在无需创造更多子类情况下,扩展对象功能。
3 架构
  • Component 接口: 抽象构件 定义了对象的接口,可以给这些对象动态增加功能
  • ConcreteComponent 具体类: 具体构件 定义了具体的构件对象,实现了 在抽象构件中声明的方法,装饰器可以给它增加额外的职责(方法)
  • Decorator 抽象类: 装饰类 抽象装饰类是抽象构件类的子类,用于给具体构件增加职责,但是具 体职责在其子类中实现;
  • ConcreteDecorator 具体类: 具体装饰类 具体装饰类是抽象装饰类的子类,负责向构 件添加新的职责。
4 案例4.1 恶心的java I/O类库
Java I/O类库几十个类,负责I/O数据的读取和写入:

针对不同读取和写入场景,又在这四个父类基础之上,扩展子类:

比如打开文件test.txt,从中读取数据。InputStream是抽象类:
  • FileInputStream,专用读取文件流的子类
  • BufferedInputStream,支持带缓存功能的数据读取类,可以提高数据读取的效率。
InputStream in = new FileInputStream("/user/javaedge/test.txt");
InputStream bin = new BufferedInputStream(in);
byte[] data = https://www.songbingjia.com/android/new byte[128];
while (bin.read(data) != -1)
//...

看着还真麻烦,得先创建一个FileInputStream,再传给BufferedInputStream使用。我在想,为何不直接设计个继承FileInputStream且支持缓存的BufferedFileInputStream?这样就能直接创建一个BufferedFileInputStream对象,打开文件读取数据,用着不是很简单吗?
InputStream bin = new BufferedFileInputStream("/user/javaegde/test.txt");
byte[] data = https://www.songbingjia.com/android/new byte[128];
while (bin.read(data) != -1)
//...

4.1.1 继承设计若InputStream只有一个子类FileInputStream,在FileInputStream基础上,再设计个孙类BufferedFileInputStream,也能接受,毕竟继承结构简单。但实际上,继承InputStream的子类有很多。需要给每个InputStream子类,再继续派生支持缓存读取的子类。
除了支持缓存读取,若还需增强其它功能,如DataInputStream支持按基本数据类型读取数据:
FileInputStream in = new FileInputStream("/user/wangzheng/test.txt");
DataInputStream din = new DataInputStream(in);
int data = https://www.songbingjia.com/android/din.readInt();

这样,若继续使用继承,就需再派生DataFileInputStream、DataPipedInputStream等类。若还需既支持缓存、又支持基本类型读取数据的类,就得再继续派生BufferedDataFileInputStream、BufferedDataPipedInputStream等n多类。这还只是附加了俩功能,若还需附加更多增强功能,就会导致组合爆炸,类继承结构无比复杂,代码既不好扩展,也不好维护。
4.1.2 装饰器模式设计“组合优于继承”,针对这种继承复杂问题,通过改为组合关系即可解决:
public abstract class InputStream
//...
public int read(byte b[]) throws IOException
return read(b, 0, b.length);


public int read(byte b[], int off, int len) throws IOException
//...


public long skip(long n) throws IOException
//...


public int available() throws IOException
return 0;


public void close() throws IOException

public synchronized void mark(int readlimit)

public synchronized void reset() throws IOException
throw new IOException("mark/reset not supported");


public boolean markSupported()
return false;



public class BufferedInputStream extends InputStream
protected volatile InputStream in;

protected BufferedInputStream(InputStream in)
this.in = in;


//...实现基于缓存的读数据接口...


public class DataInputStream extends InputStream
protected volatile InputStream in;

protected DataInputStream(InputStream in)
this.in = in;


//...实现读取基本类型数据的接口

装饰器模式就是简单的“用组合替代继承”?当然不是啦。从IO案例看,装饰器模式相比简单的组合关系,还有两个特殊点:
  • 装饰器类和原始类继承同样的父类,这样我们可以对原始类“嵌套”多个装饰器类
    如对FileInputStream嵌套俩装饰器类:BufferedInputStream和DataInputStream,让它支持缓存、按基本数据类型读取数据。
InputStream in = new FileInputStream("/user/javaedge/test.txt");
InputStream bin = new BufferedInputStream(in);
DataInputStream din = new DataInputStream(bin);
int data = https://www.songbingjia.com/android/din.readInt();

  • 装饰器类是对功能的增强,这也是装饰器模式应用场景的一个重要特点
    其实符合“组合关系”的设计模式很多,如代理模式、桥接模式。尽管代码结构相似,但意图不同。比较相似的代理模式和装饰器模式,代理模式中,代理类附加的是跟原始类无关功能,装饰器模式中,装饰器类附加的是跟原始类相关的增强功能。
// 代理模式的代码结构(下面的接口也可以替换成抽象类)
public interface IA
void f();

public class A impelements IA
public void f()//...

public class AProxy impements IA
private IA a;
public AProxy(IA a)
this.a = a;


public void f()
// 新添加的代理逻辑
a.f();
// 新添加的代理逻辑



// 装饰器模式的代码结构(下面的接口也可以替换成抽象类)
public interface IA
void f();

public class A impelements IA
public void f()//...

public class ADecorator impements IA
private IA a;
public ADecorator(IA a)
this.a = a;


public void f()
// 功能增强代码
a.f();
// 功能增强代码


BufferedInputStream、DataInputStream并非继承自InputStream,而是FilterInputStream。这是啥设计原则,要引入这个类?
【大厂是怎么实践装饰器模式的()】InputStream是抽象类而非接口,大部分函数(如read()、available())都有默认实现,按理只需在BufferedInputStream类中重新实现那些需要增加缓存功能的函数,其他函数继承InputStream的默认实现。但这行不通。
即使无需增加缓存功能的函数,BufferedInputStream也得将其重新实现,简单封装对InputStream对象的函数调用:若不重新实现,BufferedInputStream就无法将最终读取数据的任务,委托给传递进来的InputStream对象
public class BufferedInputStream extends InputStream
protected volatile InputStream in;

protected BufferedInputStream(InputStream in)
this.in = in;


// f()函数无需增强,只是重新调用InputStream in对象的f()
public void f()
in.f();


DataInputStream也有这种问题。为避免代码重复,Java IO抽象出一个装饰器父类FilterInputStream:InputStream的所有装饰器类(BufferedInputStream、DataInputStream)都继承自该装饰器父类。这样,装饰器类只需实现它需增强的方法,其他方法继承装饰器父类的默认实现。
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();


4.2 窗口
窗口接口
public interface Window
// 绘制窗口
public void draw();
// 返回窗口的描述
public String getDescription();

无滚动条功能的简单窗口实现
public class SimpleWindow implements Window

@Override
public void draw()
// 绘制窗口


@Override
public String getDescription()
return "simple window";


以下类包含所有Window类的decorator,以及修饰类本身。
//抽象装饰类 注意实现Window接口
public abstract class WindowDecorator implements Window
// 被装饰的Window
protected Window decoratedWindow;

public WindowDecorator (Window decoratedWindow)
this.decoratedWindow = decoratedWindow;


@Override
public void draw()
decoratedWindow.draw();


@Override
public String getDescription()
return decoratedWindow.getDescription();




// 第一个具体装饰器 添加垂直滚动条功能
public class VerticalScrollBar extends WindowDecorator
public VerticalScrollBar(Window windowToBeDecorated)
super(windowToBeDecorated);


@Override
public void draw()
super.draw();
drawVerticalScrollBar();


private void drawVerticalScrollBar()
// Draw the vertical scrollbar


@Override
public String getDescription()
return super.getDescription() + ", including vertical scrollbars";




// 第二个具体装饰器 添加水平滚动条功能
public class HorizontalScrollBar extends WindowDecorator
public HorizontalScrollBar (Window windowToBeDecorated)
super(windowToBeDecorated);


@Override
public void draw()
super.draw();
drawHorizontalScrollBar();


private void drawHorizontalScrollBar()
// Draw the horizontal scrollbar


@Override
public String getDescription()
return super.getDescription() + ", including horizontal scrollbars";


4.3 mybatis

5 优点使用装饰模式来实现扩展比继承更加灵活,它以对客户透明的方式动态地给一个对象附加更多的责任。装饰模式可以在不需要创造更多子类的情况下,将对象的功能加以扩展。
与继承相比,关联关系的优势在于不破坏类的封装性,而且继承是一种耦合度较大的静态关系,无法在程序运行时动态扩展。
可通过动态方式扩展一个对象的功能,通过配置文件可以在运行时选择不同装饰器,从而实现不同行为。
在软件开发阶段,关联关系虽然不会比继承关系减少编码量,但到了软件维护阶段,由于关联关系使系统具有较好的低耦合性,所以更容易维护。
通过使用不同具体装饰类以及这些装饰类的排列组合,可以创造出很多不同行为的组合。可以使用多个具体装饰类来装饰同一对象,得到功能更强大的对象。
具体构件类与具体装饰类可以独立变化,用户可以根据需要增加新的具体构件类、具体装饰类,在使用时再对其进行组合,原有代码无须改变,符合“开闭原则”。
6 缺点产生很多小对象,这些对象区别在于它们之间相互连接的方式不同,而不是它们的类或属性值不同,同时还将产生很多具体装饰类。这些装饰类和小对象的产生将增加系统的复杂度,加大学习与理解的难度。
比继承更灵活,也意味着比继承更易出错,排查也更困难,对于多次装饰的对象,调试时寻找错误可能需要逐级排查,较为烦琐。
7 适用场景在不影响其他对象的情况下,以动态、透明的方式给单个对象添加职责。
需要动态地给一个对象增加功能,这些功能也可以动态地被撤销。
当不能采用继承的方式对系统进行扩充或者采用继承不利于系统扩展和维护时。
不能采用继承的场景:
  • 系统存在大量独立扩展,为支持每一种组合将产生大量的子类,使得子类数目呈爆炸性增长
  • 类定义不能继承(如final类)
V.S 代理模式
对于添加缓存这个场景,使用哪种模式,要看设计者意图:
  • 设计者不需要用户关注是否使用了缓存功能,要隐藏实现细节,即用户只能看到和使用代理类,那就使用代理模式
  • 反之,若设计者需要用户自己决定是否使用缓存功能,需要用户自己新建原始对象并动态添加缓存功能,就使用decorator模式
代理模式和装饰者模式都是代码增强:
  • 前者偏重业务无关,高度抽象,和稳定性较高的场景(性能其实可以抛开不谈)
  • 后者偏重业务相关,定制化诉求高,改动较频繁的场景
缓存一般都是高度抽象,全业务通用,基本不会改动,所以一般也是采用代理模式,让业务开发从缓存代码的重复劳动中解放。但若当前业务的缓存实现需要特殊化定制,需揉入业务属性,就该采用装饰者模式。因其定制性强,其他业务也用不着,而且业务是频繁变动的,所以改动的可能也大,相对于动代,装饰者在调整(修改和重组)代码这件事上显得更灵活。
8 扩展一个装饰类的接口必须与被装饰类的接口保持相同,对于客户端来说无论是装饰之前的对象还是装饰之后的对象都可以一致对待。
尽量保持具体构件类的轻量,也就是说不要把太多的逻辑和状态放在具体构件类中,可以通过装饰类对其进行扩展。
装饰模式分类:
  • 透明装饰模式 要求客户端完全针对抽象编程,装饰模式的透明性要求客户端程序不应该声明具体构件类型和具体装饰类型,而应该全部声明为抽象构件类型
  • 半透明装饰模式 允许用户在客户端声明具体装饰者类型的对象,调用在具体装饰者中新增的方法
9 总结装饰器模式主要解决继承复杂的问题,使用组合替代继承,来给原始类添加增强功能。
装饰器模式还有一个特点,能对原始类嵌套使用多个装饰器。为满足该应用场景,在设计时,装饰器类需要跟原始类继承相同的抽象类或接口。
参考
  • ??https://zh.wikipedia.org/wiki/%E4%BF%AE%E9%A5%B0%E6%A8%A1%E5%BC%8F#/??

    推荐阅读