场景:对现有方法或类的增强,与代理模式不同的是,代理模式一般增强的是与原有的功能不相关的功能,比如流量统计
基于继承的装饰器模式
(1)定义接口
java
/**
* 策略模式:不同类型选择不同的实现策略
* */
public interface AbstractStrategy {
/**
* 模版模式:不同策略实现同一接口的共性部分(公共方法)
* */
default void commentMeth(){
System.out.println("模版方法");
}
void handle(Object object);
}
(2)被装饰者
java
public class AchieveOneStrategy implements AbstractStrategy{
@Override
public void handle(Object obj) {
System.out.println("hello world!");
}
}
(3)抽象的装饰者
java
public abstract class Decoration implements AbstractStrategy {
AbstractStrategy abstractStrategy;
Decoration(AbstractStrategy abstractStrategy){
this.abstractStrategy = abstractStrategy;
}
public void handle(Object object) {
abstractStrategy.handle(object);
}
}
(4)具体的装饰者
java
public class CustomDecoration extends Decoration{
CustomDecoration(AbstractStrategy abstractStrategy){
super(abstractStrategy);
}
@Override
public 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后置操作....");
}
}
比如:线程安全的List装饰器
java
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();
SynchronizedList(List<T> list){
this.list = list;
}
@Override
public boolean add(T t) {
synchronized (obj){
return list.add(t);
}
}
@Override
public T get(int index) {
synchronized (obj) {
return list.get(index);
}
}
......
}
}