我猜你正在寻找的是所谓的代理模式。
代理(顾名思义)是一个代替另一个目前不可用的对象的对象。
您可能希望以java.util.Observable
这种方式实现它
public class ObservableProxy extends Observable {
private ObservableProxyAdapter observableProxyAdapter = new ObservableProxyAdapter();
private Observable target;
public void setTarget(Observable target) {
if(this.target != null){
// if this proxy was connected to an observer... disconnect
this.target.deleteObserver(observableProxyAdapter);
}
this.target = target;
if(this.target != null){
// If a new target is set... connect to it
this.target.addObserver(observableProxyAdapter);
}
}
private class ObservableProxyAdapter implements Observer {
public void update(Observable o, Object arg) {
// forward notifications from the target
setChanged();
notifyObservers(arg);
}
}
}
你分ObservableProxy
发给客户。客户可以将自己注册到ObservableProxy
. 稍后当“真正的” Observable 可用时,您可以将其设置为ObservableProxy
. 代理将自己注册为Observer
目标并将通知转发给它的观察者。
+-----------------+ notify +---------------+ notify +--------------+
| real observable | ------> | proxy adapter | ------> | observables |
+-----------------+ +---------------+ | of proxy |
+--------------+
这是一个示例应用程序
public class ObservableProxyTest {
public static void main(String[] args) {
ObservableProxy observableProxy = new ObservableProxy();
Observer someObserver = new Observer() {
public void update(Observable o, Object arg) {
System.out.println(arg);
}
};
observableProxy.addObserver(someObserver);
// Later the real observer becomes available
RealObservable realProxy = new RealObservable();
observableProxy.setTarget(realProxy);
// notifications will be forwarded
realProxy.notifyHello();
}
private static class RealObservable extends Observable {
public void notifyHello(){
setChanged();
super.notifyObservers("Hello World");
}
}
}