在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 19:22:08  来源:igfitidea点击:

Observable in Java

javaoopdesign-patternsobserver-pattern

提问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");
        }
    }

}
  1. The bag.addObserver()can be made only because IntegerDataBagextends Observable?

  2. Where is this observer being add to? What is being created and where?

  3. What is the difference between setChanged()and notifyObservers()?

  4. I don't understand the updatemethod; what does argstand for? Why do I need to check that o==bag? Why would I update another observable?

  5. Why should I need this observer anyway?

  1. bag.addObserver()可制成只是因为IntegerDataBag延伸Observable

  2. 这个观察者被添加到哪里?正在创建什么?在哪里创建?

  3. setChanged()和 和有什么不一样notifyObservers()

  4. 我不明白这个update方法;代表什么arg?为什么我需要检查o==bag?为什么我要更新另一个 observable?

  5. 为什么我需要这个观察者?

采纳答案by S.L. Barth - Reinstate Monica

  1. Yes. addObserveris a method in the Observableabstract class. See Observablein the Java documentation.
  2. It is added to a list in Observable.
  3. A call to notifyObserverswill do nothing until setChangedis set.
  4. You might have multiple Observables in the same application.
  5. Observeris 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.
  1. 是的。addObserverObservable抽象类中的方法。请参阅Java 文档中的Observable
  2. 它被添加到Observable.
  3. 在设置notifyObservers之前调用不会做任何事情setChanged
  4. 您可能在同一个应用程序中有多个 Observable。
  5. 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 IntegerDataBaghas 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 IntegerDataBagand will receive messages through it's callback method (update).

在这里,我们也这样做。IntegerDataBag每当一个值被添加到它的内部包或从它的内部包中删除时,该类有能力通知其他类。任何实例(实现Observer)都可以将自己注册到IntegerDataBag并且将通过它的回调方法 ( update)接收消息。

In short, we do the following:

简而言之,我们执行以下操作:

  1. A observer(listener, IntegerAdder) adds itself to an observable(IntegerDataBag)
  2. Something happens at the observableand the observablenotifies its observers
  3. The observablewill call the callback methods of all actual observers
  4. The observernow has been notified of the event and can use it
  1. 观察者(监听器,IntegerAdder)增加了自身的可观察到的IntegerDataBag
  2. 事情发生在观察到的观察的通知其观察员
  3. 观察到的将调用一切实际的回调方法观察
  4. 观察员目前已收到活动通知,并可以使用它

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, Observableis a class that has the addObserver()method.

正确,Observable是一个有addObserver()方法的类。

Where is this observer being add to? what being created and where?

这个观察者被添加到哪里?正在创建什么?在哪里创建?

The Observerclass contains a Listor Vector(in the JDK source) of Observableobjects.

Observer类包含一个ListVector(在JDK源)Observable对象。

private Vector obs;

That's where it's stored.

那就是它存储的地方。

What is the different between setChanged()and notifyObservers()?

setChanged()和之间有什么区别notifyObservers()

The setChanged()just marks the Observableis 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 setChangedis 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 Observerthat it needs to update based on the changed objit 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 Listenerfor 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 addObservermethod 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 Observableas 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 Observercan watch multiple Observables. By examining the first parameter of the updatemethod, 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.

回答你的观点。

  1. Yes you're correct

  2. The observer is added to a list maintained in the Observable object

  3. 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.

  4. arg is anything you'd like to pass to Observers when you call notifyObservers(arg);

  1. 是的,你是对的

  2. 观察者被添加到一个由 Observable 对象维护的列表中

  3. 您需要在通知观察者之前调用 setChanged() ,否则他们将不知道对象已更改。一旦您调用 notifyObservers(),所有观察者都会收到有关更改的通知。如果您不先调用 setChanged,则不会通知您的观察者。

  4. 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 IntegerAdderto the list of classes that observe IntegerDatabagfor changes. From now on, if a change occurs on IntegerDataBag, it will notify IntegerAddervia 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 argis 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 IntegerDatabagthat triggered update(), hence o==bag.

由于观察者可以“观察”多个“可观察”,因此您需要检查它是否真的IntegerDatabag被触发update(),因此o==bag

Why should I need this observer anyway?

为什么我需要这个观察者?

You need the observer to monitor IntegerDataBagfor changes. In your case, you print a message in the console when IntegerDatabagis 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 模型的目的是专门监控特定对象的变化,然后根据变化更新程序。