装饰器模式是一种结构型设计模式,它允许在运行时动态地扩展对象的行为,不用修改原始对象的代码。它通过将对象包装在一个包装器类中来实现这一点,该包装器类具有与原始对象相同的接口,并且在委托给原始对象之前或之后添加额外的行为。
装饰器模式通常用于以下两种情况:
我们通过一个示例来看看它是如何实现的。在下面的示例中,我们将实现一个BoundedSet
——JAVA中大小限制的集合。
public abstract class ForwardingSet<T> implements Set<T> {
public abstract Set<T> delegate();
@Override
public int size() {
return delegate().size();
}
@Override
public boolean isEmpty() {
return delegate().isEmpty();
}
@Override
public boolean contAIns(Object o) {
return delegate().contains(o);
}
@Override
public Iterator<T> iterator() {
return delegate().iterator();
}
@Override
public Object[] toArray() {
return delegate().toArray();
}
@Override
public <T1> T1[] toArray(T1[] a) {
return delegate().toArray(a);
}
@Override
public boolean add(T t) {
return delegate().add(t);
}
@Override
public boolean remove(Object o) {
return delegate().remove(o);
}
@Override
public boolean containsAll(Collection<?> c) {
return delegate().containsAll(c);
}
@Override
public boolean addAll(Collection<? extends T> c) {
return delegate().addAll(c);
}
@Override
public boolean retainAll(Collection<?> c) {
return delegate().retainAll(c);
}
@Override
public boolean removeAll(Collection<?> c) {
return delegate().removeAll(c);
}
@Override
public void clear() {
delegate().clear();
}
}
ForwardingSet
是受google Guava库中的ForwardingSet
启发而来的。这个集合只是将其所有方法调用委托给底层委托对象,这是一种组合关系。委托是指我们将所有的调用都派发到底层对象进行处理,而在处理之前可以修改其行为。现在,我们可以继承这个类并覆盖任何方法以修改它们的行为,就像我们在BoundedSet
中所做的那样。
@ThreadSafe
public class BoundedSet<T> extends ForwardingSet<T> {
private Set<T> set;
private Semaphore semaphore;
public BoundedSet(int bound) {
this.semaphore = new Semaphore(bound);
this.set = Collections.synchronizedSet(new HashSet<>());
}
@Override
public boolean add(T t) {
try {
semaphore.acquire();
boolean wasAdded = super.add(t);
if (!wasAdded) {
semaphore.release();
}
return wasAdded;
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
@Override
public boolean remove(Object o) {
boolean wasRemoved = super.remove(o);
if (wasRemoved) {
semaphore.release();
}
return wasRemoved;
}
@Override
public boolean addAll(Collection<? extends T> c) {
try {
boolean setChanged = false;
for(var e : c) {
semaphore.acquire();
boolean wasAdded = super.add(e);
if(!wasAdded) {
semaphore.release();
}
setChanged |= wasAdded;
}
return setChanged;
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
@Override
public boolean removeAll(Collection<?> c) {
boolean setChanged = false;
for(var e : c) {
boolean wasRemoved = super.remove(e);
if(wasRemoved) {
semaphore.release();
}
setChanged |= wasRemoved;
}
return setChanged;
}
@Override
public Set<T> delegate() {
return this.set;
}
}
在这里,我们修改了add、remove、addAll和removeAll方法的行为。对于每个add,我们从信号量中获取一个许可。对于每个remove,我们添加一个许可。由于在这里使用的是不可扩展的同步集合,因此实现有点简单,但是您可以理解其思想。要使用这个类,请执行以下操作:
Set<Integer> set = new BoundedSet<>(10);
在Spring中,装饰器大量用于在进入对象之前拦截对它们的调用。在我们的情况下,我们必须解决Java中线程切换时在两个线程之间传输MDC的棘手问题。MDC是一种在日志记录期间传输上下文信息的机制,例如请求ID或用户ID等信息。我们通过装饰相应执行器服务的submit
方法来解决这个问题,以获取调用线程的MDC,将其复制到当前线程的MDC(在runnable内部),然后将调用派发到底层委托。以下是代码:
ForwardedExecutorService.java
public abstract class ForwardedExecutorService implements ExecutorService {
public abstract ExecutorService delegate();
@Override
public void shutdown() {
delegate().shutdown();
}
@Override
public List<Runnable> shutdownNow() {
return delegate().shutdownNow();
}
@Override
public boolean isShutdown() {
return delegate().isShutdown();
}
@Override
public boolean isTerminated() {
return delegate().isTerminated();
}
@Override
public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
return delegate().awaitTermination(timeout, unit);
}
@Override
public <T> Future<T> submit(Callable<T> task) {
return delegate().submit(task);
}
@Override
public <T> Future<T> submit(Runnable task, T result) {
return delegate().submit(task, result);
}
@Override
public Future<?> submit(Runnable task) {
return delegate().submit(task);
}
@Override
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException {
return delegate().invokeAll(tasks);
}
@Override
public <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException {
return delegate().invokeAll(tasks, timeout, unit);
}
@Override
public <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException {
return delegate().invokeAny(tasks);
}
@Override
public <T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException {
return delegate().invokeAny(tasks, timeout, unit);
}
@Override
public void execute(Runnable command) {
delegate().execute(command);
}
}
MDCAwareExecutorService.java
public class MDCAwareExecutorService extends ForwardedExecutorService {
private ExecutorService es;
public MDCAwareExecutorService() {
this.es = Executors.newCachedThreadPool();
}
@Override
public ExecutorService delegate() {
return this.es;
}
@Override
public <T> Future<T> submit(Callable<T> task) {
return super.submit(decorateTask(task));
}
@Override
public <T> Future<T> submit(Runnable task, T result) {
return super.submit(decorateTask(task), result);
}
@Override
public Future<?> submit(Runnable task) {
return super.submit(decorateTask(task));
}
@Override
public void execute(Runnable command) {
super.execute(decorateTask(command));
}
private <V> Callable<V> decorateTask(Callable<V> task) {
//获取当前线程的MDC
Map<String, String> mdc = MDC.METADATA.get();
return () -> {
MDC.METADATA.set(mdc);
return task.call();
};
}
private Runnable decorateTask(Runnable task) {
//获取当前线程的MDC
Map<String, String> mdc = MDC.METADATA.get();
return () -> {
MDC.METADATA.set(mdc);
task.run();
};
}
}
MDC.java
public class MDC {
public static ThreadLocal<Map<String, String>> METADATA = new ThreadLocal<>();
}
Driver.java
public class Driver {
public static void main(String[] args) throws InterruptedException {
MDC.METADATA.set(Map.of("k1","v1","k2","v2"));
var es = new MDCAwareExecutorService();
es.submit(() -> {
System.out.println("Thread: " + Thread.currentThread().getName() + ", MDC: " + MDC.METADATA.get());;
});
Thread.sleep(Integer.MAX_VALUE);
}
}