场景:对现有方法或类的增强,与代理模式不同的是,代理模式一般增强的是与原有的功能不相关的功能,比如流量统计
结构图
基于继承的装饰器模式
(1)定义接口
/*** 策略模式:不同类型选择不同的实现策略* */
public interface AbstractStrategy {/*** 模版模式:不同策略实现同一接口的共性部分(公共方法)* */default void commentMeth(){System.out.println("模版方法");}void handle(Object object);
}
(2)被装饰者
public class AchieveOneStrategy implements AbstractStrategy{@Overridepublic void handle(Object obj) {System.out.println(obj + "hello world!");}
}
(3)抽象的装饰者
public abstract class Decoration implements AbstractStrategy {AbstractStrategy abstractStrategy;public Decoration(AbstractStrategy abstractStrategy){this.abstractStrategy = abstractStrategy;}public void handle(Object object) {abstractStrategy.handle(object);}}
(4)具体的装饰者
public class CustomDecoration extends Decoration{public CustomDecoration(AbstractStrategy abstractStrategy){super(abstractStrategy);}@Overridepublic void handle(Object object) {before();abstractStrategy.handle(object);after();}public void before(){System.out.println("ConcreteDecorator前置操作....");}/*** 具体组件动作执行后的装饰** @author zdp* @date 2022/9/3 17:58*/public void after(){System.out.println("ConcreteDecorator后置操作....");}}
(5)测试
public class TestOne {public static void main(String[] args) throws InterruptedException {AchieveOneStrategy achieveOneStrategy = new AchieveOneStrategy();CustomDecoration customDecoration = new CustomDecoration(achieveOneStrategy);customDecoration.handle("tom");}
}
实用举例:线程安全的List装饰器
public class SynchronizedCollections {static <T> List<T> synchronizedList(List<T> list){return new SynchronizedList<>(list);}static class SynchronizedList<T> implements List<T> {List<T> list;final Object obj = new Object();public SynchronizedList(List<T> list){this.list = list;}@Overridepublic boolean add(T t) {synchronized (obj){return list.add(t);}}@Overridepublic T get(int index) {synchronized (obj) {return list.get(index);}}......}
}