我们什么时候应该使用Observer和Observable? [英] When should we use Observer and Observable?

查看:392
本文介绍了我们什么时候应该使用Observer和Observable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一位采访者问我:

什么是观察员可观察我们什么时候应该使用它们?

What is Observer and Observable and when should we use them?

我不知道这些条款,所以当我回到家并开始谷歌搜索 Observer Observable ,我从不同的资源中找到了一些积分:

I wasn't aware of these terms, so when I got back home and started Googling about Observer and Observable, I found some points from different resources:


1) Observable 是一个类, Observer 是一个界面。

1) Observable is a class and Observer is an interface.

2 ) Observable 类维护一个 Observer 的列表。

2) The Observable class maintains a list of Observers.

3)当更新 Observable 对象时,它会调用每个 update()方法。 c $ c> Observer s通知,它已被更改。

3) When an Observable object is updated, it invokes the update() method of each of its Observers to notify that, it is changed.

我找到了这个例子:

import java.util.Observable;
import java.util.Observer;

class MessageBoard extends Observable
{
    public void changeMessage(String message) 
    {
        setChanged();
        notifyObservers(message);
    }
}

class Student implements Observer 
{
    @Override
    public void update(Observable o, Object arg) 
    {
        System.out.println("Message board changed: " + arg);
    }
}

public class MessageBoardTest 
{
    public static void main(String[] args) 
    {
        MessageBoard board = new MessageBoard();
        Student bob = new Student();
        Student joe = new Student();
        board.addObserver(bob);
        board.addObserver(joe);
        board.changeMessage("More Homework!");
    }
}

但我不明白为什么我们需要 Observer Observable ?什么是 setChanged() notifyObservers(消息)方法?

But I don't understand why we need Observer and Observable? What are the setChanged() and notifyObservers(message) methods for?

推荐答案

你有一个学生和一个MessageBoard的具体例子。学生通过将自己添加到希望在将新消息发布到MessageBoard时得到通知的观察者列表进行注册。当消息被添加到MessageBoard时,它会遍历其观察者列表并通知他们事件发生。

You have a concrete example of a Student and a MessageBoard. The Student registers by adding itself to the list of Observers that want to be notified when a new Message is posted to the MessageBoard. When a Message is added to the MessageBoard, it iterates over its list of Observers and notifies them that the event occurred.

想想Twitter。如果您想跟随某人,Twitter会将您添加到他们的关注者列表中。当他们发送新推文时,您会在输入中看到它。在这种情况下,您的Twitter帐户是观察者,您关注的人是Observable。

Think Twitter. When you say you want to follow someone, Twitter adds you to their follower list. When they sent a new tweet in, you see it in your input. In that case, your Twitter account is the Observer and the person you're following is the Observable.

这个比喻可能并不完美,因为Twitter更有可能是调解员。但它说明了这一点。

The analogy might not be perfect, because Twitter is more likely to be a Mediator. But it illustrates the point.

这篇关于我们什么时候应该使用Observer和Observable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆