我們什麼時候應該使用Observer和Observable? - When should we use Observer and Observable?

問題:

An interviewer asked me: 一位採訪者問我:

What is Observer and Observable and when should we use them? 什麼是ObserverObservable以及我們何時應該使用它們?

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: 我不知道這些術語,所以當我回到家並開始使用Googling ObserverObservable ,我從不同的資源中找到了一些觀點:

1) Observable is a class and Observer is an interface. 1) Observable是一個類, Observer是一個接口。

2) The Observable class maintains a list of Observer s. 2) Observable類維護一個Observer列表。

3) When an Observable object is updated, it invokes the update() method of each of its Observer s to notify that, it is changed. 3)更新Observable對象時,它會調用每個Observerupdate()方法來通知它,它會被更改。

I found this example: 我找到了這個例子:

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

But I don't understand why we need Observer and Observable ? 但我不明白爲什麼我們需要ObserverObservable What are the setChanged() and notifyObservers(message) methods for? 什麼是setChanged()notifyObservers(message)方法?


解決方案:

參考一: https://en.stackoom.com/question/vfYg
參考二: https://stackoom.com/question/vfYg
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章