结构性设计模式(三)装饰器模式【给爱用继承的人一个全新的设计思路】

曾经的梦想是可以继承一切,直到领教到了运行时扩展,远比编译期间继承的威力大。

一、概念

1.1 什么是装饰器模式?

装饰器模式主要解决继承关系过于复杂的问题,通过组合来替代继承。

  • 装饰器模式主要的作用是给原始类添加增强功能,这也是判断是否该用装饰器模式的一个重要的依据。
  • 装饰器可以在任何时候被装饰,所以可以运行时动态的,不限量的用你喜欢的装饰者来装饰对象,可以对原始类嵌套使用多个装饰器。
  • 为了满足这个场景应用,装饰器类需要跟原始类继承相同的抽象类或者接口。
  • 你可以为一个或者多个装饰者包装一个对象。

1.2 通用实现类图

在这里插入图片描述
如果不理解,没有关系,继续往下看,举例说明。

二、继承多了会爆炸

继承属于扩展形式之一,但不见得是达到弹性设计的最佳方案。

举个《Head First 设计模式》里的例子

场景一:咖啡馆想要做一个订单系统,有HouseBlend(综合咖啡)、DarkRoast(深度烘焙)、Decaf(脱咖啡因咖啡)、Espresso(蒸馏咖啡)等几种咖啡。

场景二:咖啡馆为了吸引更多的顾客,需要在订单系统中允许顾客选择加入不同调料的咖啡,例如:蒸奶(Steamed Milk)、豆浆(Soy)、摩卡(Mocha,也就是巧克力风味)或覆盖奶泡。

场景三:后续还可能推出大杯、中杯、小杯。

场景四:星巴兹会根据所加入的调料、杯型收取不同的费用,所以订单系统必须考虑到这些部分。

如果使用继承的话,duang,爆炸了···
在这里插入图片描述

三、如何使用装饰者模式去解决问题

利用继承设计子类的行为,是在编译时决定的,而且所有的子类都会继承相同的行为,然而,如果能够利用组合的做法扩展对象的行为,就可以在运行时动态的进行扩展。

我们要以饮料为主体,然后在运行时以调料来“装饰”(decorate)饮料。比方说,如果顾客想要摩卡和奶泡深焙咖啡,那么,要做的是:

  1. 拿一个深焙咖啡(DarkRoast)对象
  2. 以摩卡(Mocha)对象装饰它
  3. 以奶泡(Whip)对象装饰它
  4. 调用cost()方法,并依赖委托(delegate)将调料的价钱加上去。
    在这里插入图片描述
    结合装饰者模式的概念,让咖啡厅也实现这个模式,类图如下
    在这里插入图片描述
    具体实现如下
//抽象类,有两个方法,getDescription() and cost()
public abstract class Beverage {

  String description = "unknown Beverage";
  
  public String getDescription() {
    return description;
  }
  public abstract double cost();
}
//调料的抽象类,也就是装饰者类,为了方便实现调料的一些处理逻辑
public abstract class CondimentDecorator extends Beverage {
  @Override
  public abstract String getDescription();
}

饮料的代码如下

//饮料代码Espresso 
public class Espresso extends Beverage {

  public Espresso() {
    description = "Espresso";
  }

  @Override
  public double cost() {
    return 1.99;
  }
}

//饮料代码House Blend
public class HouseBlend extends Beverage {

  public HouseBlend() {
    description = "House Blend Coffee";
  }

  @Override
  public double cost() {
    return 0.89;
  }
}

饮料的具体实现,注意CondimentDecorator扩展自Beverage

//调料代码 Mocha
public class Mocha extends CondimentDecorator {
  Beverage beverage;

  public Mocha(Beverage beverage) {
    this.beverage = beverage;
  }

  @Override
  public String getDescription() {
    return beverage.getDescription() + ", Mocha";
  }

  @Override
  public double cost() {
    return 0.20 + beverage.cost();
  }
}

//调料代码 Soy
public class Soy extends CondimentDecorator {
  Beverage beverage;

  public Soy(Beverage beverage) {
    this.beverage = beverage;
  }

  @Override
  public String getDescription() {
    return beverage.getDescription() + ", Soy";
  }

  @Override
  public double cost() {
    return 0.25 + beverage.cost();
  }
}

//调料代码 Soy
public class Whip extends CondimentDecorator {
  Beverage beverage;

  public Whip(Beverage beverage) {
    this.beverage = beverage;
  }

  @Override
  public String getDescription() {
    return beverage.getDescription() + ", Whip";
  }

  @Override
  public double cost() {
    return 0.35 + beverage.cost();
  }
}

运行程序,开始点杯咖啡

public class StarbuzzCoffee {

  public static void main(String[] args) {
    //什么都不加的咖啡
    Beverage beverage = new Espresso();
    System.out.println(beverage.getDescription() + " $" + beverage.cost());
    //加三份mocha 一分soy 一分whip的咖啡
    Beverage beverage1 = new HouseBlend();
    beverage1 = new Mocha(beverage1);
    beverage1 = new Mocha(beverage1);
    beverage1 = new Mocha(beverage1);
    beverage1 = new Soy(beverage1);
    beverage1 = new Whip(beverage1);
    System.out.println(beverage1.getDescription() + " $" + beverage1.cost());
  }
}

运行结过如下:
在这里插入图片描述
代码实现可以参见 【github】.实现

四、java IO中的装饰者模式

Java IO 类库非常庞大和复杂,有几十个类,负责 IO 数据的读取和写入。如果对 Java IO 类做一下分类,从下面两个维度将它划分为四类。具体如下所示:
在这里插入图片描述
针对不同的读取和写入场景,Java IO 又在这四个父类基础之上,扩展出了很多子类。具体如下所示:
在这里插入图片描述
抽象出必要的代码结构


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;
  }
  
  //...实现读取基本类型数据的接口

从 Java IO 的设计来看,装饰器模式相对于简单的组合关系,还有两个比较特殊的地方。

第一个比较特殊的地方是:装饰器类和原始类继承同样的父类,这样我们可以对原始类嵌套多个装饰器类。

比如,下面这样一段代码,我们对 FileInputStream 嵌套了两个装饰器类:BufferedInputStream 和 DataInputStream,让它既支持缓存读取,又支持按照基本数据类型来读取数据。

InputStream in = new FileInputStream("/user/wangzheng/test.txt");
InputStream bin = new BufferedInputStream(in);
DataInputStream din = new DataInputStream(bin);
int data = 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();
    // 功能增强代码
  }
}

如果去查看 JDK 的源码,你会发现,BufferedInputStream、DataInputStream 并非继承自 InputStream,而是另外一个叫 FilterInputStream 的类。那这又是出于什么样的设计意图,才引入这样一个类呢?

我们再重新来看一下 BufferedInputStream 类的代码。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 也存在跟 BufferedInputStream 同样的问题。为了避免代码重复,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();
  }
}

五、编写自己的java IO装饰类

编写一个装饰者,把输入流内的所有大写字符转成小写。举例:当读取 I like YOU,装饰者将它转换成 i like you

public class LowerCaseInputStream extends FilterInputStream {

  public LowerCaseInputStream(InputStream in) {
    super(in);
  }
 
  //一个针对字节,一个针对字节数组
  @Override
  public int read() throws IOException {
    int c = super.read();
    return (c == -1 ? c : Character.toLowerCase((char) c));
  }

  @Override
  public int read(byte[] b, int off, int len) throws IOException {
    int result = super.read(b, off, len);
    for (int i = off; i < off + result; i++) {
      b[i] = (byte) Character.toLowerCase((char) b[i]);
    }
    return result;
  }
}
public class InputTest {
  public static void main(String[] args) {
    int c;
    try {
      //装饰它
      InputStream in =
          new LowerCaseInputStream(new BufferedInputStream(new FileInputStream("test.txt")));
      //用流来读取字符,一直到文件尾端,每读取一个字符,就马上将它显示出来
      while ((c = in.read()) >= 0) {
        System.out.print((char) c);
      }
      in.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

六、装饰者模式的缺点

利用装饰者模式,常常造成设计中有大量的小类,数量实在太多,可能会造成使用此API程序员的困扰。

不过熟悉了结构之后,看起来就会好很多

七、主要参考内容

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值