Design Pattern-Decorator

装饰者模式

别称:包装模式、装饰器模式、Wrapper、Decorator

装饰器模式(Decorator Pattern)允许在不改变其结构的情况下向一个现有的对象添加新的功能。

结构

  1. 抽象构件 (Component)
  2. 具体构件 (Concrete Component)
  3. 抽象装饰类 (Decorator)
  4. 具体装饰类 (Concrete Decorators)

简单示例

装饰器模式| 菜鸟教程

画图形:图形有长方形、圆形;可以画红色的也可以画绿色的。

抽象构件

1
2
3
public interface Shape {
void draw();
}

具体构件

1
2
3
4
5
6
public class Rectangle implements Shape {
@Override
public void draw() {
System.out.print("Shape: rectangle\t");
}
}
1
2
3
4
5
6
public class Circle implements Shape {
@Override
public void draw() {
System.out.print("Shape: circle\t");
}
}

抽象装饰类

1
2
3
4
5
6
7
public abstract class ShapeDecorator implements Shape {
protected Shape shape;

public ShapeDecorator(Shape shape) {
this.shape = shape;
}
}

具体装饰类

1
2
3
4
5
6
7
8
9
10
11
public class RedShapeDecorator extends ShapeDecorator {
public RedShapeDecorator(Shape shape) {
super(shape);
}

@Override
public void draw() {
shape.draw();
System.out.println("Color: red");
}
}
1
2
3
4
5
6
7
8
9
10
11
public class GreenShapeDecorator extends ShapeDecorator {
public GreenShapeDecorator(Shape shape) {
super(shape);
}

@Override
public void draw() {
shape.draw();
System.out.println("Color: green");
}
}

客户端使用

1
2
3
4
5
6
7
8
9
10
11
12
13
public static void main(String[] args) {
Shape shape = new RedShapeDecorator(new Rectangle());
shape.draw();

shape = new GreenShapeDecorator(new Rectangle());
shape.draw();

shape = new RedShapeDecorator(new Circle());
shape.draw();

shape = new GreenShapeDecorator(new Circle());
shape.draw();
}
1
2
3
4
Shape: rectangle	Color: red
Shape: rectangle Color: green
Shape: circle Color: red
Shape: circle Color: green

典型应用

设计模式| 装饰者模式及典型应用 - 掘金

Java I/O

抽象构件:java.io.InputStream

具体构件:

  • java.io.FileInputStream

  • java.io.ByteArrayInputStream

  • java.io.PipedInputStream

抽象装饰类:java.io.FilterInputStream

具体装饰类:

  • java.io.BufferedInputStream

  • java.io.DataInputStream

  • java.io.PushbackInputStream

实例化一个具有缓存功能的字节流对象时,只需要在 FileInputStream 对象上再套一层 BufferedInputStream 对象即可。

1
2
FileInputStream fileInputStream = new FileInputStream(filePath);
BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);

DataInputStream 装饰者提供了对更多数据类型进行输入的操作,比如 int、double 等基本类型。