装饰器模式
应用场景: 拓展一个类的功能或给一个类添加附加职责.
优点:
- 不改变原有对象的情况下给一个对象拓展功能
- 使用不同的组合实现不同的效果
- 符合开闭原则

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| interface Component{ void operation(); }
class ConcreteComponent implements Component{ @Override public void operation() { System.out.println("拍照"); } }
class ConcreteComponent1 implements Component {
private Component component; public ConcreteComponent1(Component component) { this.component = component; }
@Override public void operation() { System.out.println("美颜"); component.operation(); } }
new ConcreteComponent1(new ConcreteComponent()).operation();
|
也可以把装饰器抽象出来
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| interface Component{ void operation(); }
class ConcreateComponent implements Component{ @Override public void operation() { System.out.println("拍照"); } }
abstract class Decorator implements Component{ Component component;
public Decorator(Component component) { this.component = component; }
@Override public void operation() { component.operation(); } }
class ConcreateComponent1 extends Decorator{
public ConcreateComponent1(Component component) { super(component); }
@Override public void operation() { System.out.println("美颜"); super.operation(); } }
class ConcreateComponent2 extends Decorator{
public ConcreateComponent2(Component component) { super(component); }
@Override public void operation() { System.out.println("呵呵"); super.operation(); } }
ConcreateComponent2 concreateComponent1 = new ConcreateComponent2(new ConcreateComponent1(new ConcreateComponent())); concreateComponent1.operation();
|
https://www.bilibili.com/video/BV1hp4y1D7MP?from=search&seid=6785978722248254154
https://www.bilibili.com/video/BV1Hv411r7uN?p=2