设计模式-装饰模式 Decorator

本文详细介绍了装饰器模式的原理,包括如何在Java中实现以及其在I/O库中的应用。通过实例展示了如何使用装饰器动态为对象添加行为,特别强调了装饰器模式在处理复杂I/O类库时的优势。
摘要由CSDN通过智能技术生成

1) 原理

装饰器设计模式(Decorator)是一种结构型设计模式,它允许动态地为对象添加新的行为。它通过创建一个包装器来实现,即将对象放入一个装饰器类中,再将装饰器类放入另一个装饰器类中,以此类推,形成一条包装链。这样,我们可以在不改变原有对象的情况下,动态地添加新的行为或修改原有行为

在 Java 中,实现装饰器设计模式的步骤如下:

1、定义一个接口或抽象类,作为被装饰对象的基类。

public interface Component {
    void operation();
}

在这个示例中,我们定义了一个名为 Component 的接口,它包含一个名为 operation 的抽象方法,用于定义被装饰对象的基本行为。

2、定义一个具体的被装饰对象,实现基类中的方法。

public class ConcreteComponent implements Component{
    @Override
    public void operation() {
        System.out.println("这是未被包装的原始类");
    }
}

在这个示例中,我们定义了一个名为 ConcreteComponent 的具体实现类,实现了 Component 接口中的 operation 方法。

3、定义一个抽象装饰器类,继承基类,并将被装饰对象作为属性。

public abstract class Decorator implements Component {
    // 装饰器设计模式使用组合的形式进行装饰
    Component component;

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

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

在这个示例中,我们定义了一个名为 Decorator 的抽象类,继承了 Component 接口,并将被装饰对象作为属性。在 operation 方法中,我们调用被装饰对象的同名方法。

4、定义具体的装饰器类,继承抽象装饰器类,并实现增强逻辑。

public class DecoratorOne extends Decorator{
    public DecoratorOne(Component component) {
        super(component);
    }

    @Override
    public void operation() {
        System.out.println("这是前边添加了行为! 第一次包装");
        super.operation();
        System.out.println("这是后边添加了行为! 第一次包装");
    }
}
public class DecoratorTwo extends Decorator{
    public DecoratorTwo(Component component) {
        super(component);
    }

    @Override
    public void operation() {
        System.out.println("这是前边添加了行为! 第二次包装");
        super.operation();
        System.out.println("这是后边添加了行为! 第二次包装");
    }
}

在这个示例中,我们定义了一个名为 DecoratorOneDecoratorTwo 的具体装饰器类,继承了 Decorator 抽象类,并实现了 operation 方法的增强逻辑。在 operation 方法中,我们先调用被装饰对象的同名方法,然后添加新的行为。

5、使用装饰器增强被装饰对象。

public class Main {
    public static void main(String[] args) {
        // 1. 创建一个原始对象
        Component component = new ConcreteComponent();

        // 2.进行第一次包装
        component = new DecoratorOne(component);

        // 3.进行第二次包装
        component = new DecoratorTwo(component);

        component.operation();
    }
}
这是前边添加了行为! 第二次包装
这是前边添加了行为! 第一次包装
这是未被包装的原始类
这是后边添加了行为! 第一次包装
这是后边添加了行为! 第二次包装

2) 使用场景

在 Java 中,装饰器模式的应用非常广泛,特别是在 I/O 操作中。Java 中的 I/O 类库就是使用装饰器模式来实现不同的数据流之间的转换和增强的。

1、从IO库的设计理解装饰器

在初学 Java 的时候,曾经对 Java IO 的一些用法产生过很大疑惑,比如下面这样一段代码。我们打开文件 test.txt,从中读取数据。其中,InputStream 是一个抽象类,FileInputStream 是专门用来读取文件流的子类。BufferedInputStream 是一个支持带缓存功能的数据读取类,可以提高数据读取的效率,具体的代码如下:

@Test
void test() throws Exception {
    // 1.创建一个IO流
    InputStream input = new FileInputStream("F:/news.txt");
    // 2.读取
    byte[] buffer = new byte[1024];
    int len;
    while ((len = input.read(buffer)) != -1) {
        System.out.println(new String(buffer, 0, len));
    }
    // 3.关闭流
    input.close();
}

初看上面的代码,我们会觉得 Java IO 的用法比较麻烦,需要先创建一个 FileInputStream 对象,然后再传递给 BufferedInputStream 对象来使用。Java IO 为什么不设计一个继承 FileInputStream 并且支持缓存的 BufferedFileInputStream 类呢?这样我们就可以像下面的代码中这样,直接创建一个 BufferedFileInputStream 类对象,打开文件读取数据,用起来岂不是更加简单?

// 1.创建一个IO流
InputStream input = new FileInputStream("F:/news.txt");
input = new BufferedInputStream(input);

(1) 基于继承的设计方案

如果 InputStream 只有一个子类 FileInputStream 的话,那我们在 FileInputStream 基础之上,再设计一个孙子类 BufferedFileInputStream,也算是可以接受的,毕竟继承结构还算简单。但实际上,继承 InputStream 的子类有很多。我们需要给每一个 InputStream 的子类,再继续派生支持缓存读取的子类。

除了支持缓存读取之外,如果我们还需要对功能进行其他方面的增强,比如下面的 DataInputStream 类,支持按照基本数据类型(int、boolean、long 等)来读取数据。

FileInputStream in = new FileInputStream("/user/wangzheng/test.txt");
DataInputStream din = new DataInputStream(in);
int data = din.readInt();

在这种情况下,如果我们继续按照继承的方式来实现的话,就需要再继续派生出 DataFileInputStream、DataPipedInputStream 等类。如果我们还需要既支持缓存、又支持按照基本类型读取数据的类,那就要再继续派生出 BufferedDataFileInputStream、BufferedDataPipedInputStream 等 n 多类。这还只是附加了两个增强功能,如果我们需要附加更多的增强功能,那就会导致组合爆炸,类继承结构变得无比复杂,代码既不好扩展,也不好维护。

(2) 基于装饰器模式的设计方案

“组合优于继承”,可以“使用组合来替代继承”。针对刚刚的继承结构过于复杂的问题,可以通过将继承关系改为组合关系来解决。下面的代码展示了 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;
  }
  
  //...实现读取基本类型数据的接口
}

**第一个比较特殊的地方是:装饰器类和原始类继承同样的父类,这样我们可以对原始类“嵌套”多个装饰器类。**比如,下面这样一段代码,我们对 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();
            // 功能增强代码
        }
}
  • 24
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值