我的第一个想法是引入一个额外的间接级别。您的控件可以是代理对象(实现相同的接口)的订阅者,而不是真实对象CarStop
和Car
对象,然后代理对象又知道他们的“真实”伙伴,并且能够在后者被替换为新伙伴时更新对他们的伙伴的引用.
interface ICarStop {
void addObserver(CarStopObserver observer);
void removeObserver(CarStopObserver observer);
}
class CarStopControl implements CarStopObserver {
public void update (ICarStop obj, Object arg) {
// ...
}
}
class CarStopProxy implements ICarStop {
ICarStop original;
public CarStopProxy(ICarStop original) {
this.original = original;
}
public void setOriginal(ICarStop original) {
this.original = original;
}
public void addObserver(CarStopObserver observer) {
// ...
}
public void removeObserver(CarStopObserver observer) {
// ...
}
public void notifyObservers(Object object) {
// iterate through observers an update each
}
}
class CarStop implements ICarStop {
CarStopProxy proxy;
public CarStop(CarStopProxy proxy) {
this.proxy = proxy;
}
public CarStop(CarStop other) {
// copy all properties
this.proxy = other.proxy;
}
public CarStopProxy getProxy() {
return proxy;
}
public void setProxy(CarStopProxy proxy) {
this.proxy = proxy;
}
public void handleChange() {
proxy.notifyObservers(...);
}
}
现在,当您需要替换 CarStop 对象时,您可以编写:
CarStop newCarStop = new CarStop(oldCarStop);
// update all references to point to the new object
oldCarStop.setProxy(null);
另一种可能性是引入一个Mediator,它能够通过某种标识符来识别模型对象(不同于它们的具体地址/引用,因为它可以改变)。在这种情况下,当一个CarStop
对象被另一个对象替换时,新对象只是接管其前身的 ID,并在其更新消息中使用它:
class CarStop implements ICarStop {
Mediator mediator;
Long id;
public CarStop(Mediator mediator) {
this.mediator = mediator;
}
public CarStop(CarStop other) {
// copy all properties
this.mediator = other.mediator;
}
public void handleChange() {
mediator.notifyObservers(id, ...);
}
}
CarStop newCarStop = new CarStop(oldCarStop);
// update all references to point to the new object