作用: 可以在不改动原有代码的情况下,对现有的对象、行为进行新的层次的包装、装饰,增强原有的基本功能以提供更丰富的能力。
使用场景: 需要增强的目标存在抽象接口,且功能不足
结构图
使用 以墙面装修为例子
?1.定义一个墙面装修接口
public interface WallBeautify {
void operation();
}
?2.接口的实现类
public class WallBeautifyClean implements WallBeautify {
@Override
public void operation() {
System.out.println("开始清理墙面");
}
}
?3.定义一个装饰器抽象类,对装修方法进行增强
- 装饰器也实现了基本的装修接口
- 覆盖了原有的
operation() 方法,在此基础上进行增强
public abstract class WallBeautifyDecorator implements WallBeautify {
private WallBeautify wallBeautify;
public WallBeautifyDecorator(WallBeautify wallBeautify) {
this.wallBeautify = wallBeautify;
}
@Override
public void operation() {
wallBeautify.operation();
decoration();
}
public abstract void decoration();
}
?4.定义装饰器抽象类的各个实现类
public class WallBeautifyPutty extends WallBeautifyDecorator {
public WallBeautifyPutty(WallBeautify wallBeautify) {
super(wallBeautify);
}
@Override
public void decoration() {
System.out.println("开始刮腻子");
}
}
public class WallBeautifyPaint extends WallBeautifyDecorator {
public WallBeautifyPaint(WallBeautify wallBeautify) {
super(wallBeautify);
}
@Override
public void decoration() {
System.out.println("开始涂油漆");
}
}
public class WallBeautifyHang extends WallBeautifyDecorator {
public WallBeautifyHang(WallBeautify wallBeautify) {
super(wallBeautify);
}
@Override
public void decoration() {
System.out.println("开始挂壁画");
}
}
?5.增强
public class DecoratorTest {
public static void main(String[] args) {
WallBeautify wallBeautifyClean = new WallBeautifyClean();
wallBeautifyClean.operation();
System.out.println("--------------");
WallBeautify wallBeautifyPutty = new WallBeautifyPutty(wallBeautifyClean);
wallBeautifyPutty.operation();
System.out.println("--------------");
WallBeautify wallBeautifyPaint = new WallBeautifyPaint(wallBeautifyPutty);
wallBeautifyPaint.operation();
System.out.println("--------------");
WallBeautify wallBeautifyHang = new WallBeautifyHang(wallBeautifyPaint);
wallBeautifyHang.operation();
System.out.println("--------------");
WallBeautify wbh = new WallBeautifyHang(new WallBeautifyPaint(
new WallBeautifyPutty(new WallBeautifyClean())));
wbh.operation();
System.out.println("--------------");
}
}
参考资料: 1.https://www.cnblogs.com/V1haoge/p/10472321.html 2.https://mp.weixin.qq.com/s?__biz=MzI3ODcxMzQzMw==&mid=2247558483&idx=1&sn=66e3d98e22c029c7ca141debfadff253
|