在 Java 中可观察
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7271044/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Observable in Java
提问by Numerator
I'm trying to understand the Observer and the Observable.
我试图理解观察者和观察者。
Here's an example that I'm trying to figure out:
这是我试图弄清楚的一个例子:
public class IntegerDataBag extends Observable implements Iterable<Integer> {
private ArrayList<Integer> list= new ArrayList<Integer>();
public void add(Integer i){
list.add(i);
setChanged();
notifyObservers();
}
public Iterator<Integer> iterator(){
return list.iterator();
}
public Integer remove (int index){
if (index< list.size()){
Integer i = list.remove(index);
setChanged();
notifyObservers();
return i;
}
return null;
}
}
public class IntegerAdder implements Observer {
private IntegerDataBag bag;
public IntegerAdder(IntegerDataBag bag) {
this.bag = bag;
bag.addObserver(this);
}
public void update(Observable o, Object arg) {
if (o == bag) {
System.out.println("The contents of the IntegerDataBag have changed");
}
}
}
The
bag.addObserver()
can be made only becauseIntegerDataBag
extendsObservable
?Where is this observer being add to? What is being created and where?
What is the difference between
setChanged()
andnotifyObservers()
?I don't understand the
update
method; what doesarg
stand for? Why do I need to check thato==bag
? Why would I update another observable?Why should I need this observer anyway?
该
bag.addObserver()
可制成只是因为IntegerDataBag
延伸Observable
?这个观察者被添加到哪里?正在创建什么?在哪里创建?
setChanged()
和 和有什么不一样notifyObservers()
?我不明白这个
update
方法;代表什么arg
?为什么我需要检查o==bag
?为什么我要更新另一个 observable?为什么我需要这个观察者?
采纳答案by S.L. Barth - Reinstate Monica
- Yes.
addObserver
is a method in theObservable
abstract class. See Observablein the Java documentation. - It is added to a list in
Observable
. - A call to
notifyObservers
will do nothing untilsetChanged
is set. - You might have multiple Observables in the same application.
Observer
is a common design pattern. The usual example is when you have a Model and multiple Views. Each View is an Observer on the Model; if the Model changes, the Views get updated.
- 是的。
addObserver
是Observable
抽象类中的方法。请参阅Java 文档中的Observable。 - 它被添加到
Observable
. - 在设置
notifyObservers
之前调用不会做任何事情setChanged
。 - 您可能在同一个应用程序中有多个 Observable。
Observer
是一种常见的设计模式。通常的例子是当你有一个模型和多个视图时。每个视图都是模型上的观察者;如果模型更改,则视图会更新。
回答by Andreas Dolk
Let's take a practical example for Observer pattern: Twitter. With Twitter we can followsome other people and read whatever they post in near realtime.
让我们举一个观察者模式的实际例子:Twitter。通过 Twitter,我们可以关注其他人,并几乎实时阅读他们发布的任何内容。
Every twitter user is observable. You can add yourself as a listener ("Follower") and read his/her posts. Every twitter user will do a "notify Followers" (notifyObservers
).
每个 twitter 用户都是可观察的。您可以将自己添加为听众(“关注者”)并阅读他/她的帖子。每个 Twitter 用户都会做一个“通知关注者”(notifyObservers
)。
Here we do the same. The class IntegerDataBag
has the capability to notify other classes whenever a value is added to or deleted from it's internal bag. Any instance (that implements Observer
) can register itself to an IntegerDataBag
and will receive messages through it's callback method (update
).
在这里,我们也这样做。IntegerDataBag
每当一个值被添加到它的内部包或从它的内部包中删除时,该类有能力通知其他类。任何实例(实现Observer
)都可以将自己注册到IntegerDataBag
并且将通过它的回调方法 ( update
)接收消息。
In short, we do the following:
简而言之,我们执行以下操作:
- A observer(listener,
IntegerAdder
) adds itself to an observable(IntegerDataBag
) - Something happens at the observableand the observablenotifies its observers
- The observablewill call the callback methods of all actual observers
- The observernow has been notified of the event and can use it
- 甲观察者(监听器,
IntegerAdder
)增加了自身的可观察到的(IntegerDataBag
) - 事情发生在观察到的和观察的通知其观察员
- 该观察到的将调用一切实际的回调方法观察
- 该观察员目前已收到活动通知,并可以使用它
Hope, this short description helps in understanding this pattern.
希望,这个简短的描述有助于理解这种模式。
publish/subscribe is a similiar pattern: a publisher is like an observable, a subscriber like an observer. And another practical example: one can subscribe to a newspaper and the publisher will send the paper until you cancel your subscription.
发布/订阅是一种类似的模式:发布者就像一个可观察对象,订阅者就像一个观察者。另一个实际例子:一个人可以订阅一份报纸,出版商会发送报纸,直到您取消订阅。
回答by Buhake Sindi
The bag.addObserver() can be made only because IntegerDataBag extends Observable?
bag.addObserver() 只能因为 IntegerDataBag 扩展了 Observable 才可以制作?
Correct, Observable
is a class that has the addObserver()
method.
正确,Observable
是一个有addObserver()
方法的类。
Where is this observer being add to? what being created and where?
这个观察者被添加到哪里?正在创建什么?在哪里创建?
The Observer
class contains a List
or Vector
(in the JDK source) of Observable
objects.
的Observer
类包含一个List
或Vector
(在JDK源)Observable
对象。
private Vector obs;
That's where it's stored.
那就是它存储的地方。
What is the different between
setChanged()
andnotifyObservers()
?
setChanged()
和之间有什么区别notifyObservers()
?
The setChanged()
just marks the Observable
is changed.
The notifyObservers()
just calls the all observers it has on the list to update()
(passing a changed object to the Observer) only if the setChanged
is set to true.
在setChanged()
刚刚标记的Observable
改变。仅当设置为 true 时,notifyObservers()
才调用列表中的所有观察者update()
(将更改的对象传递给观察者)setChanged
。
I don't understand the update method- what does args stands for? and why do I need to check that o==bag, why would I update another observable?
我不明白更新方法 - args 代表什么?为什么我需要检查那个 o==bag,我为什么要更新另一个 observable?
The update()
method tells the Observer
that it needs to update based on the changed obj
it receives. This is called by the notifyObservers()
from Observable
.
该update()
方法告诉Observer
它需要根据obj
收到的更改进行更新。这由notifyObservers()
from调用Observable
。
Why should I need this observer anyway?
为什么我需要这个观察者?
To create a Listener
for event driven scenario, i.e. if you want to be informed in the change of your observable objects, then Observer is needed.
为了创建一个Listener
事件驱动的场景,即如果你想在你的可观察对象的变化中得到通知,那么需要观察者。
Read: GoF - Observer pattern.
阅读:GoF -观察者模式。
回答by Heisenbug
The bag.addObserver() can be made only because IntegerDataBag extends Observable?
bag.addObserver() 只能因为 IntegerDataBag 扩展了 Observable 才可以制作?
Yes.
是的。
2.Where is this observer being add to? what being created and where?
2.这个观察者被添加到哪里?正在创建什么?在哪里创建?
Into the related Observable class, which your class is extending.
进入相关的 Observable 类,您的类正在扩展该类。
4.I don't understand the update method- what does args stands for?
4.我不明白更新方法- args 代表什么?
It's called when the state of an observed object has changed. The args is the parameter passed to nofityObserver.
当观察对象的状态发生变化时调用它。args 是传递给 nofityObserver 的参数。
and why do I need to check that o==bag, why would I update another observable?
为什么我需要检查那个 o==bag,我为什么要更新另一个 observable?
You don't need to check anything.
你不需要检查任何东西。
5.Why should I need this observer anyway?
5.我为什么需要这个观察者?
It's a very useful design pattern. Have a look to wikipedia article.
这是一个非常有用的设计模式。看看维基百科文章。
EDIT: I missed point :
编辑:我错过了点:
What is the different between setChanged() and notifyObservers()?
setChanged() 和 notifyObservers() 有什么区别?
setChanged() marks an object signalling that it changed. notifyObservers is responsible to wake all observer listening to the observable object.
setChanged() 标记一个对象,表明它已更改。notifyObservers 负责唤醒所有监听 observable 对象的观察者。
回答by ddso
The bag.addObserver() can be made only because IntegerDataBag extends Observable?
bag.addObserver() 只能因为 IntegerDataBag 扩展了 Observable 才可以制作?
Yes, the addObserver
method is implemented in Observable
.
是的,该addObserver
方法是在Observable
.
Where is this observer being add to? what being created and where?
这个观察者被添加到哪里?正在创建什么?在哪里创建?
The observer is being added to a list of observers which is declared in Observable
as private, so it is not visible in your subclass.
观察者被添加到被声明Observable
为私有的观察者列表中,因此它在您的子类中不可见。
What is the different between setChanged() and notifyObservers()?
setChanged() 和 notifyObservers() 有什么区别?
When you call notifyObservers()
without first calling setChanged()
, no notifications take place.
当您在notifyObservers()
未先拨打电话的情况下拨打电话时setChanged()
,不会发出通知。
I don't understand the update method- what does args stands for? and why do I need to check that o==bag, why would I update another observable?
我不明白更新方法 - args 代表什么?为什么我需要检查那个 o==bag,我为什么要更新另一个 observable?
One Observer
can watch multiple Observables
. By examining the first parameter of the update
method, you can figure out which observer is notifying you about something.
一个Observer
可以看多个Observables
。通过检查该update
方法的第一个参数,您可以确定哪个观察者正在通知您某事。
Why should I need this observer anyway?
为什么我需要这个观察者?
Any time you want a class to send events to other classes but you don't want a direct dependency from that class on its observers.
任何时候您希望一个类向其他类发送事件,但又不希望该类直接依赖于它的观察者。
回答by WaelJ
The observer pattern is similar to the concept of listeners. The object which is being listened to maintains a record of all of it's listeners. For instance, a stock monitor class may allow objects to listen for a certain event, such as the stock level falling below the warning level.
观察者模式类似于听众的概念。被监听的对象维护着它所有监听者的记录。例如,库存监视器类可能允许对象侦听某个事件,例如库存水平低于警告水平。
From the observer's point of view:
从观察者的角度来看:
Call subscribe()
or addEventListener()
or the like. The observer is then "notified" when the event actually occurs, usually by means of calling a function in the observer (the event handler function).
呼叫subscribe()
或addEventListener()
等。当事件实际发生时,观察者会被“通知”,通常是通过调用观察者中的一个函数(事件处理函数)。
from the observable's point of view:
从 observable 的角度来看:
Objects wishing to observe the observable object register their interest by calling the subscribe()
or addEventListener()
as above. The observable thus adds these observers to an array, list, or some other data structure.
希望观察可观察对象的对象通过调用subscribe()
或addEventListener()
如上所述来注册他们的兴趣。observable 因此将这些观察者添加到数组、列表或其他一些数据结构中。
Once the event actually happens, the listeners are notified by calling the event handler function in the observers' class.
一旦事件真正发生,通过调用观察者类中的事件处理函数来通知监听者。
回答by Benjamin Udink ten Cate
The update() method is called by the Observable. This method is called by calling notifyObservers(), which itterates trough all Observers and calls update on them. This informs the Observer that the object they are watching has been changed and a certain action can be performed. The args object is whatever you want it to be, it can be null aswell but it can be used to inform the observers what type of update just took place.
update() 方法由 Observable 调用。这个方法是通过调用notifyObservers() 来调用的,它遍历所有的观察者并调用它们的更新。这通知观察者他们正在观察的对象已经改变并且可以执行某个动作。args 对象是你想要的任何东西,它也可以为空,但它可以用来通知观察者刚刚发生了什么类型的更新。
回答by extorn
In answer to your points.
回答你的观点。
Yes you're correct
The observer is added to a list maintained in the Observable object
You need to call setChanged() before you notify observers, otherwise they won't know the object has changed. Once you call notifyObservers(), All obvserers are notified of the change. If you don't call setChanged first, your observers won't be notified.
arg is anything you'd like to pass to Observers when you call notifyObservers(arg);
是的,你是对的
观察者被添加到一个由 Observable 对象维护的列表中
您需要在通知观察者之前调用 setChanged() ,否则他们将不知道对象已更改。一旦您调用 notifyObservers(),所有观察者都会收到有关更改的通知。如果您不先调用 setChanged,则不会通知您的观察者。
arg 是您在调用 notifyObservers(arg) 时想要传递给观察者的任何内容;
回答by Matt Fortier
The bag.addObserver() can be made only because IntegerDataBag extends Observable?
bag.addObserver() 只能因为 IntegerDataBag 扩展了 Observable 才可以制作?
Yes, that's the whole point.
是的,这就是重点。
Where is this observer being add to? what is being created and where?
这个观察者被添加到哪里?正在创建什么?在哪里创建?
It adds IntegerAdder
to the list of classes that observe IntegerDatabag
for changes. From now on, if a change occurs on IntegerDataBag
, it will notify IntegerAdder
via the notifyObservers()
method, which will trigger its update()
method.
它添加IntegerAdder
到观察IntegerDatabag
变化的类列表中。从现在开始,如果在 上发生更改IntegerDataBag
,它将IntegerAdder
通过notifyObservers()
方法通知,该方法将触发其 update()
方法。
What is the difference between setChanged() and notifyObservers()?
setChanged() 和 notifyObservers() 有什么区别?
notifyObservers()
calls the update()
method of every observer of your observable, and is used to pass infos to this method. As for setChanged()
, it marks your object as "changed" so that the hasChanged()
method will now return true... It's used to monitor changes to your observable class.
notifyObservers()
调用update()
可观察对象的每个观察者的方法,并用于将信息传递给此方法。至于setChanged()
,它将您的对象标记为“已更改”,以便该hasChanged()
方法现在将返回 true...它用于监视您的 observable 类的更改。
I don't understand the update method- what does args stands for?
我不明白更新方法 - args 代表什么?
The update()
method is inherited from the implementation of the observer interface - You have to implement it. The Object arg
is an optional argument that you can pass to the method via notifyObservers()
.
该update()
方法是从观察者接口的实现继承的 - 您必须实现它。该Object arg
是一个可选参数,你可以传递给通过方法notifyObservers()
。
Why do I need to check that o==bag, why would I update another observable?
为什么我需要检查那个 o==bag,我为什么要更新另一个 observable?
Since an observer can "observe" more than one "observable", you need to check that it's really IntegerDatabag
that triggered update()
, hence o==bag
.
由于观察者可以“观察”多个“可观察”,因此您需要检查它是否真的IntegerDatabag
被触发update()
,因此o==bag
。
Why should I need this observer anyway?
为什么我需要这个观察者?
You need the observer to monitor IntegerDataBag
for changes. In your case, you print a message in the console when IntegerDatabag
is modified. The purpose of the Observer/Observable model is specifically to monitor changes on specific objects, and then update the program based on the changes.
您需要观察者来监视IntegerDataBag
变化。在您的情况下,您在IntegerDatabag
修改时在控制台中打印一条消息。Observer/Observable 模型的目的是专门监控特定对象的变化,然后根据变化更新程序。