如何将此模式应用于返回 Future 的东西?
我认为您必须在这里实现自己的代理Future
类。可能类似于以下委托给代理的内容:
public class FutureProxy implements Future<Integer> {
private Calculator calculator;
private Future<Integer> delegate;
public FutureProxy(Calculator calculator, Future<Integer> delegate) {
this.calculator = calculator;
this.delegate = delegate;
}
// proxy all of the methods
public boolean isDone() {
return delegate.isDone();
}
...
// for get, you can then call back to `calculator`
public Integer get() throws InterruptedException, ExecutionException {
Integer result = delegate.get();
calculator.setCachedCalculation(result);
return result;
}
// need to handle get(long, TimeUnit) as well
public Integer get(long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
Integer result = delegate.get(timeout, unit);
calculator.setCachedCalculation(result);
return result;
}
}
然后你的装饰吸气剂看起来像:
public Future<Integer> getCalculation() {
Future<Integer> future = realObject.getCalculation();
return new FutureProxy(this, future);
}
正如您在评论中提到的,如果FutureProxy
是装饰器的内部类,则Calculator
不会被注入。如果代理正在更新将由其他线程访问的volatile
字段,请确保您使用字段。Calculator