在 Observer class 中访问 Observable class 的方法
Accessing methods of Observable class in Observer class
如何从 Observer class 中的 Observable class 访问 method/instance,其中 method/instance 不是被观察的对象。
例如,如果这些 getter 方法在我的 Observable class 中,但只有书被观察到,我将如何访问名称并存储在我的 Observer class 中(即在update() 方法)?
public class MethodEx extends Observable {
...
public String getName(){
return this.name;
}
public String getBook(){
return this.book;
}
public String getStore(){
return this.store;
}
}
您通常将观察到的对象与事件一起传递。这是在 ChangeListener
which uses a ChangeEvent
中完成的。 ChangeEvent
有一个 getSource
方法可以告诉哪个对象被更改了。
翻译成你的术语,你会做
public String setBook(Book book) {
this.book = book;
for (UpdateListener listener : listeners)
listener.updated(new UpdateEvent(this));
}
如何从 Observer class 中的 Observable class 访问 method/instance,其中 method/instance 不是被观察的对象。
例如,如果这些 getter 方法在我的 Observable class 中,但只有书被观察到,我将如何访问名称并存储在我的 Observer class 中(即在update() 方法)?
public class MethodEx extends Observable {
...
public String getName(){
return this.name;
}
public String getBook(){
return this.book;
}
public String getStore(){
return this.store;
}
}
您通常将观察到的对象与事件一起传递。这是在 ChangeListener
which uses a ChangeEvent
中完成的。 ChangeEvent
有一个 getSource
方法可以告诉哪个对象被更改了。
翻译成你的术语,你会做
public String setBook(Book book) {
this.book = book;
for (UpdateListener listener : listeners)
listener.updated(new UpdateEvent(this));
}