装饰者模式

类图

代码

1
2
3
interface Component{
void operation();
}
1
2
3
4
5
6
7
class ConcreteComponent implements Component{

@Override
public void operation() {
System.out.println("原始操作");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
class Decorator implements Component{

private Component component;

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

@Override
public void operation() {
component.operation();
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
class ConcreteDecorator extends Decorator{

public ConcreteDecorator(Component component) {
super(component);
}

@Override
public void operation() {
System.out.println("操作前");
super.operation();
System.out.println("操作后");
}
}

测试类

1
2
3
4
5
6
7
8
9
10
11
12
13
class ConcreteDecorator extends Decorator{

public ConcreteDecorator(Component component) {
super(component);
}

@Override
public void operation() {
System.out.println("操作前");
super.operation();
System.out.println("操作后");
}
}

结果

1
2
3
操作前
原始操作
操作后

总结

概述

1.什么时候使用装饰者

需要扩展一个类的功能,或给一个类添加附加职责

2.实际场景的使用者

Java中的InputStream,FilterInputStream,BufferedInputStream大量使用了装饰者模式

优点

  1. 相对于继承,可以提供更多的灵活性扩展类的功能
  2. 通过不同的装饰方法,可以创造出很多不同行为的组合

缺点

  1. 会相对引入较多的子类,增加系统的复杂度
  2. 装饰者模式会面对Component进行操作的,如果原系统中操作是针对ConcreteComponent的,那么将变的不适用