我们什么时候应该使用观察者和可观察的

时间:2022-09-11 11:40:55

An interviewer asked me:

面试官问我:

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

什么是观察者和可观察的,我们应该在什么时候使用它们?

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

我不知道这些术语,所以当我回到家,我开始在谷歌上搜索观察者和可观察性,并从不同的资源中找到一些点:

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

1) Observable是一个类,Observer是一个接口。

2) Observable class maintain a list of Observers.

2)可观察类保持一个观察者列表。

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

3)当一个可观察对象被更新时,它调用每个观察者的update()方法来通知这个对象被更改。

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? What are the setChanged() and notifyObservers(message) methods for?

但我不明白为什么我们需要观察者和可观察的人?setChanged()和notifyobserver(消息)方法用于什么?

10 个解决方案

#1


215  

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.

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

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。当你说你想追随某人时,Twitter会把你加入他们的追随者列表。当他们发送一条新的tweet进来时,你可以在你的输入中看到。在这种情况下,你的Twitter账户就是观察者,你关注的人就是观察者。

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

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

#2


48  

In very simple terms (because the other answers are referring you to all the official design patterns anyway, so look at them for further details):

用非常简单的术语来说(因为其他的答案都是指所有的官方设计模式,所以请查看它们以获得更多的细节):

If you want to have a class which is monitored by other classes in the ecosystem of your program you say that you want the class to be observable. I.e. there might be some changes in its state which you would want to broadcast to the rest of the program.

如果您想要一个由程序的生态系统中的其他类监视的类,您就说您希望这个类是可观察的。也就是说,它的状态可能会有一些变化,你想要向程序的其他部分广播。

Now, to do this we have to call some kind of method. We don't want the Observable class to be tightly coupled with the classes that are interested in observing it. It doesn't care who it is as long as it fulfils certain criteria. (Imagine it is a radio station, it doesn't care who is listening as long as they have an FM radio tuned on their frequency). To achieve that we use an interface, referred to as the Observer.

要做到这一点,我们必须调用某种方法。我们不希望可观察类与有兴趣观察它的类紧密耦合。只要它符合一定的标准,它并不关心它是谁。(假设这是一个广播电台,只要调频收音机就行,谁在收听就不重要了)。为了实现这一点,我们使用一个接口,称为观察者。

Therefore, the Observable class will have a list of Observers (i.e. instances implementing the Observer interface methods you might have). Whenever it wants to broadcast something, it just calls the method on all the observers, one after the other.

因此,可观察类将有一个观察者列表(例如实现观察者接口方法的实例)。每当它想广播什么东西时,它只对所有观察者调用方法,一个接一个。

The last thing to close the puzzle is how will the Observable class know who is interested? So the Observable class must offer some mechanism to allow Observers to register their interest. A method such as addObserver(Observer o) internally adds the Observer to the list of observers, so that when something important happens, it loops through the list and calls the respective notification method of the Observer interface of each instance in the list.

最后要结束这个谜题的是,可观察的类如何知道谁感兴趣?因此,可观察的类必须提供某种机制,以允许观察者登记他们的兴趣。诸如addObserver(Observer o)之类的方法在内部将观察者添加到观察者列表中,以便当发生重要的事情时,它循环遍历列表并调用列表中每个实例的观察者接口的相应通知方法。

It might be that in the interview they did not ask you explicitly about the java.util.Observer and java.util.Observable but about the generic concept. The concept is a design pattern, which Java happens to provide support for directly out of the box to help you implement it quickly when you need it. So I would suggest that you understand the concept rather than the actual methods/classes (which you can look up when you need them).

可能在面试中他们没有明确地问你关于java.util的问题。观察者和java.util。可观察,但关于一般概念。这个概念是一种设计模式,Java恰好提供了对开箱即用的支持,以帮助您在需要时快速实现它。因此,我建议您理解这个概念,而不是实际的方法/类(当您需要它们时,您可以查找它们)。

UPDATE

更新

In response to your comment, the actual java.util.Observable class offers the following facilities:

作为对您的评论的回应,实际的java.util。可观察的课程提供以下设施:

  1. Maintaining a list of java.util.Observer instances. New instances interested in being notified can be added through addObserver(Observer o), and removed through deleteObserver(Observer o).

    维护java.util列表。观察者的实例。可以通过addObserver(Observer o)添加感兴趣的新实例,并通过deleteObserver(Observer o)删除。

  2. Maintaining an internal state, specifying whether the object has changed since the last notification to the observers. This is useful because it separates the part where you say that the Observable has changed, from the part where you notify the changes. (E.g. Its useful if you have multiple changes happening and you only want to notify at the end of the process rather than at each small step). This is done through setChanged(). So you just call it when you changed something to the Observable and you want the rest of the Observers to eventually know about it.

    维护内部状态,指定自上次通知观察者以来,对象是否发生了更改。这是很有用的,因为它将可观察到的变化的部分与通知变化的部分分开。(如果你有多个变化发生,你只希望在过程的最后通知,而不是在每一个小步骤)。这是通过setChanged()实现的。当你把一些东西变成可观测的东西时你就叫它你想让其他的观察者最终知道它。

  3. Notifying all observers that the specific Observable has changed state. This is done through notifyObservers(). This checks if the object has actually changed (i.e. a call to setChanged() was made) before proceeding with the notification. There are 2 versions, one with no arguments and one with an Object argument, in case you want to pass some extra information with the notification. Internally what happens is that it just iterates through the list of Observer instances and calls the update(Observable o, Object arg) method for each of them. This tells the Observer which was the Observable object that changed (you could be observing more than one), and the extra Object arg to potentially carry some extra information (passed through notifyObservers().

    通知所有观察者,特定的可观测对象已经改变了状态。这是通过notifyobserver()实现的。在继续处理通知之前,它将检查对象是否确实发生了更改(即调用setChanged()))。有两个版本,一个没有参数,一个有对象参数,如果您想要在通知中传递一些额外的信息。在内部,它只是遍历观察者实例的列表,并为每个实例调用update(Observable o, Object arg)方法。这告诉观察者哪个是改变了的可观察对象(您可以观察多个对象),而额外的对象arg可能携带一些额外的信息(通过notifyobserver()传递)。

#3


26  

Definition

定义

Observer pattern is used when there is one to many relationship between objects such as if one object is modified, its dependent objects are to be notified automatically and corresponding changes are done to all dependent objects .

当对象之间存在一到多个关系时(例如,如果一个对象被修改,那么将自动通知它的相关对象,并对所有相关对象执行相应的更改),则使用Observer模式。

Examples

例子

  1. Lets say,your permanent address is changed then you need to notify passport authority and pan card authority.So here passport authority and pan card authority are observers and You are a subject.

    比方说,你的永久地址改变了,然后你需要通知护照部门和泛卡部门。所以这里护照管理局和潘卡当局是观察员,你是一个主题。

  2. On Facebook also,If you subscribe someone then whenever new updates happen then you will be notified.

    在Facebook上,如果你订阅了某人,那么每当有新的更新发生,你就会被通知。

When to use it:

什么时候使用它:

1. When one object changes its state,then all other dependents object must automatically change their state to maintain consistency
2. When subject doesn't know about number of observers it has.
3. When an object should be able to notify other objects without knowing who objects are.

Step 1

步骤1

Create Subject class.

创建主题类。

Subject.java

Subject.java

  import java.util.ArrayList;
  import java.util.List;

  public class Subject {

  private List<Observer> observers 
        = new ArrayList<Observer>();
  private int state;

  public int getState() {
    return state;
  }

 public void setState(int state) {
   this.state = state;
   notifyAllObservers();
 }

   public void attach(Observer observer){
     observers.add(observer);       
   }

  public void notifyAllObservers(){
    for (Observer observer : observers) {
     observer.update();
  }
}   

}

}

Step 2

步骤2

Create Observer class.

创建观察者类。

Observer.java

Observer.java

public abstract class Observer {
   protected Subject subject;
   public abstract void update();
}

Step 3

步骤3

Create concrete observer classes

创建具体观察者类

BinaryObserver.java

BinaryObserver.java

public class BinaryObserver extends Observer{

  public BinaryObserver(Subject subject){
     this.subject = subject;
     this.subject.attach(this);
  }

  @Override
  public void update() {
     System.out.println( "Binary String: " 
     + Integer.toBinaryString( subject.getState() ) ); 
  }

}

}

OctalObserver.java

OctalObserver.java

public class OctalObserver extends Observer{

   public OctalObserver(Subject subject){
     this.subject = subject;
    this.subject.attach(this);
 }

  @Override
  public void update() {
    System.out.println( "Octal String: " 
    + Integer.toOctalString( subject.getState() ) ); 
  }

}

}

HexaObserver.java

HexaObserver.java

public class HexaObserver extends Observer{

  public HexaObserver(Subject subject){
    this.subject = subject;
    this.subject.attach(this);
 }

  @Override
  public void update() {
     System.out.println( "Hex String: " 
    + Integer.toHexString( subject.getState() ).toUpperCase() ); 
}

}

}

Step 4

步骤4

Use Subject and concrete observer objects.

使用主体和具体的观察者对象。

ObserverPatternDemo.java

ObserverPatternDemo.java

 public class ObserverPatternDemo {
    public static void main(String[] args) {
       Subject subject = new Subject();

       new HexaObserver(subject);
       new OctalObserver(subject);
       new BinaryObserver(subject);

       System.out.println("First state change: 15");    
       subject.setState(15);
       System.out.println("Second state change: 10");   
       subject.setState(10);
 }

}

}

Step 5

步骤5

Verify the output.

验证输出。

First state change: 15

第一个状态变化:15

Hex String: F

十六进制字符串:F

Octal String: 17

八进制字符串:17

Binary String: 1111

二进制串:1111

Second state change: 10

第二种状态变化:10

Hex String: A

十六进制字符串:

Octal String: 12

八进制字符串:12

Binary String: 1010

二进制串:1010

#4


9  

They are parts of the Observer design pattern. Usually one or more obervers get informed about changes in one observable. It's a notifcation that "something" happened, where you as a programmer can define what "something" means.

它们是观察者设计模式的一部分。通常一个或更多的obervers会被告知一个可观察到的变化。这是一个通知,“某事”发生了,你作为一个程序员可以定义什么是“某事”的意思。

When using this pattern, you decouple the both entities from each another - the observers become pluggable.

当使用这个模式时,您可以将两个实体彼此分离——观察者变成可插入的。

#5


8  

Observer a.k.a callback is registered at Observable.

观察者a.k.。回调在可观察的地方注册。

It is used for informing e.g. about events that happened at some point of time. It is widely used in Swing, Ajax, GWT for dispatching operations on e.g. UI events (button clicks, textfields changed etc).

它被用来告知某事在某一时刻发生的事情。它广泛应用于Swing、Ajax、GWT等中,用于调度UI事件(按钮单击、文本字段更改等)的操作。

In Swing you find methods like addXXXListener(Listener l), in GWT you have (Async)callbacks.

在Swing中可以找到addXXXListener(侦听器l)之类的方法,在GWT中可以找到异步回调。

As list of observers is dynamic, observers can register and unregister during runtime. It is also a good way do decouple observable from observers, as interfaces are used.

由于观察者列表是动态的,观察者可以在运行时注册和注销。这也是一种很好的方法,可以将观察到的数据与观察者分离,因为使用了接口。

#6


6  

If the interviewer asks to implement Observer design pattern without using Observer classes and interfaces, you can use the following simple example!

如果面试官要求不使用观察者类和接口实现观察者设计模式,您可以使用以下简单的示例!

MyObserver as observer interface

interface MyObserver {

    void update(MyObservable o, Object arg);
}

MyObservable as Observable class

class MyObservable
{
    ArrayList<MyObserver> myObserverList = new ArrayList<MyObserver>();

    boolean changeFlag = false;

    public void notifyObservers(Object o)
    {
        if (hasChanged())
        {
            for(MyObserver mo : myObserverList) {
                mo.update(this, o);
            }
            clearChanged();
        }
    }


    public void addObserver(MyObserver o) {
        myObserverList.add(o);        
    }

    public void setChanged() {
        changeFlag = true;
    }

    public boolean hasChanged() {
        return changeFlag;
    }

    protected void clearChanged() {
        changeFlag = false;
    }

    // ...
}

Your example with MyObserver and MyObservable!

class MessageBoard extends MyObservable {
  private String message;

  public String getMessage() {
    return message;
  }

  public void changeMessage(String message) {
    this.message = message;
    setChanged();
    notifyObservers(message);
  }

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

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

#7


4  

"I tried to figure out, why exactly we need Observer and Observable"

"我试图弄明白,为什么我们需要观察者和可观察的"

As previous answers already stated, they provide means of subscribing an observer to receive automatic notifications of an observable.

如前所述,它们提供了订阅观察者以接收可观察的自动通知的方法。

One example application where this may be useful is in data binding, let's say you have some UI that edits some data, and you want the UI to react when the data is updated, you can make your data observable, and subscribe your UI components to the data

一个可能有用的示例应用程序是数据绑定,假设您有一些UI来编辑一些数据,并且您希望UI在数据更新时发生响应,您可以使您的数据可观察,并将您的UI组件订阅到数据。

Knockout.js is a MVVM javascript framework that has a great getting started tutorial, to see more observables in action I really recommend going through the tutorial. http://learn.knockoutjs.com/

淘汰赛。js是一个MVVM javascript框架,它有一个很好的入门教程,要查看更多的可观察的内容,我建议您阅读本教程。http://learn.knockoutjs.com/

I also found this article in Visual Studio 2008 start page (The Observer Pattern is the foundation of Model View Controller (MVC) development) http://visualstudiomagazine.com/articles/2013/08/14/the-observer-pattern-in-net.aspx

我还在Visual Studio 2008 start页面(Observer模式是Model View Controller (MVC)开发的基础)http://visualstudiomagazine.com/articles/2013/3/08/14 / The - Observer - Pattern -in-net.aspx上发现了这篇文章

#8


2  

I have written a short description of the observer pattern here: http://www.devcodenote.com/2015/04/design-patterns-observer-pattern.html

我在这里写了一个关于观察者模式的简短描述:http://www.devco去记/2015/04/design-patterns-observer-pattern.html

A snippet from the post:

文章片段:

Observer Pattern : It essentially establishes a one-to-many relationship between objects and has a loosely coupled design between interdependent objects.

观察者模式:它在对象之间建立一个一对多的关系,在相互依赖的对象之间建立一个松散耦合的设计。

TextBook Definition: The Observer Pattern defines a one-to-many dependency between objects so that when one object changes state, all of its dependents are notified and updated automatically.

教科书定义:观察者模式定义了对象之间的一对多依赖关系,因此当一个对象改变状态时,它的所有依赖关系都会被自动通知和更新。

Consider a feed notification service for example. Subscription models are the best to understand the observer pattern.

例如,考虑一个提要通知服务。订阅模型是理解观察者模式的最佳方式。

#9


0  

Observer pattern is used when there is one-to-many relationship between objects such as if one object is modified, its dependent objects are to be notified automatically.

当对象之间存在一对多关系时(例如,如果一个对象被修改,那么它的相关对象将被自动通知),则使用Observer模式。

#10


0  

Since Java9, both interfaces are deprecated, meaning you should not use them anymore. See Observer is deprecated in Java 9. What should we use instead of it?

由于Java9,这两个接口都被废弃了,这意味着您不应该再使用它们了。在Java 9中不赞成使用Observer。我们应该用什么来代替它呢?

However, you might still get interview questions about them...

然而,你可能仍然会收到关于他们的面试问题……

#1


215  

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.

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

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。当你说你想追随某人时,Twitter会把你加入他们的追随者列表。当他们发送一条新的tweet进来时,你可以在你的输入中看到。在这种情况下,你的Twitter账户就是观察者,你关注的人就是观察者。

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

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

#2


48  

In very simple terms (because the other answers are referring you to all the official design patterns anyway, so look at them for further details):

用非常简单的术语来说(因为其他的答案都是指所有的官方设计模式,所以请查看它们以获得更多的细节):

If you want to have a class which is monitored by other classes in the ecosystem of your program you say that you want the class to be observable. I.e. there might be some changes in its state which you would want to broadcast to the rest of the program.

如果您想要一个由程序的生态系统中的其他类监视的类,您就说您希望这个类是可观察的。也就是说,它的状态可能会有一些变化,你想要向程序的其他部分广播。

Now, to do this we have to call some kind of method. We don't want the Observable class to be tightly coupled with the classes that are interested in observing it. It doesn't care who it is as long as it fulfils certain criteria. (Imagine it is a radio station, it doesn't care who is listening as long as they have an FM radio tuned on their frequency). To achieve that we use an interface, referred to as the Observer.

要做到这一点,我们必须调用某种方法。我们不希望可观察类与有兴趣观察它的类紧密耦合。只要它符合一定的标准,它并不关心它是谁。(假设这是一个广播电台,只要调频收音机就行,谁在收听就不重要了)。为了实现这一点,我们使用一个接口,称为观察者。

Therefore, the Observable class will have a list of Observers (i.e. instances implementing the Observer interface methods you might have). Whenever it wants to broadcast something, it just calls the method on all the observers, one after the other.

因此,可观察类将有一个观察者列表(例如实现观察者接口方法的实例)。每当它想广播什么东西时,它只对所有观察者调用方法,一个接一个。

The last thing to close the puzzle is how will the Observable class know who is interested? So the Observable class must offer some mechanism to allow Observers to register their interest. A method such as addObserver(Observer o) internally adds the Observer to the list of observers, so that when something important happens, it loops through the list and calls the respective notification method of the Observer interface of each instance in the list.

最后要结束这个谜题的是,可观察的类如何知道谁感兴趣?因此,可观察的类必须提供某种机制,以允许观察者登记他们的兴趣。诸如addObserver(Observer o)之类的方法在内部将观察者添加到观察者列表中,以便当发生重要的事情时,它循环遍历列表并调用列表中每个实例的观察者接口的相应通知方法。

It might be that in the interview they did not ask you explicitly about the java.util.Observer and java.util.Observable but about the generic concept. The concept is a design pattern, which Java happens to provide support for directly out of the box to help you implement it quickly when you need it. So I would suggest that you understand the concept rather than the actual methods/classes (which you can look up when you need them).

可能在面试中他们没有明确地问你关于java.util的问题。观察者和java.util。可观察,但关于一般概念。这个概念是一种设计模式,Java恰好提供了对开箱即用的支持,以帮助您在需要时快速实现它。因此,我建议您理解这个概念,而不是实际的方法/类(当您需要它们时,您可以查找它们)。

UPDATE

更新

In response to your comment, the actual java.util.Observable class offers the following facilities:

作为对您的评论的回应,实际的java.util。可观察的课程提供以下设施:

  1. Maintaining a list of java.util.Observer instances. New instances interested in being notified can be added through addObserver(Observer o), and removed through deleteObserver(Observer o).

    维护java.util列表。观察者的实例。可以通过addObserver(Observer o)添加感兴趣的新实例,并通过deleteObserver(Observer o)删除。

  2. Maintaining an internal state, specifying whether the object has changed since the last notification to the observers. This is useful because it separates the part where you say that the Observable has changed, from the part where you notify the changes. (E.g. Its useful if you have multiple changes happening and you only want to notify at the end of the process rather than at each small step). This is done through setChanged(). So you just call it when you changed something to the Observable and you want the rest of the Observers to eventually know about it.

    维护内部状态,指定自上次通知观察者以来,对象是否发生了更改。这是很有用的,因为它将可观察到的变化的部分与通知变化的部分分开。(如果你有多个变化发生,你只希望在过程的最后通知,而不是在每一个小步骤)。这是通过setChanged()实现的。当你把一些东西变成可观测的东西时你就叫它你想让其他的观察者最终知道它。

  3. Notifying all observers that the specific Observable has changed state. This is done through notifyObservers(). This checks if the object has actually changed (i.e. a call to setChanged() was made) before proceeding with the notification. There are 2 versions, one with no arguments and one with an Object argument, in case you want to pass some extra information with the notification. Internally what happens is that it just iterates through the list of Observer instances and calls the update(Observable o, Object arg) method for each of them. This tells the Observer which was the Observable object that changed (you could be observing more than one), and the extra Object arg to potentially carry some extra information (passed through notifyObservers().

    通知所有观察者,特定的可观测对象已经改变了状态。这是通过notifyobserver()实现的。在继续处理通知之前,它将检查对象是否确实发生了更改(即调用setChanged()))。有两个版本,一个没有参数,一个有对象参数,如果您想要在通知中传递一些额外的信息。在内部,它只是遍历观察者实例的列表,并为每个实例调用update(Observable o, Object arg)方法。这告诉观察者哪个是改变了的可观察对象(您可以观察多个对象),而额外的对象arg可能携带一些额外的信息(通过notifyobserver()传递)。

#3


26  

Definition

定义

Observer pattern is used when there is one to many relationship between objects such as if one object is modified, its dependent objects are to be notified automatically and corresponding changes are done to all dependent objects .

当对象之间存在一到多个关系时(例如,如果一个对象被修改,那么将自动通知它的相关对象,并对所有相关对象执行相应的更改),则使用Observer模式。

Examples

例子

  1. Lets say,your permanent address is changed then you need to notify passport authority and pan card authority.So here passport authority and pan card authority are observers and You are a subject.

    比方说,你的永久地址改变了,然后你需要通知护照部门和泛卡部门。所以这里护照管理局和潘卡当局是观察员,你是一个主题。

  2. On Facebook also,If you subscribe someone then whenever new updates happen then you will be notified.

    在Facebook上,如果你订阅了某人,那么每当有新的更新发生,你就会被通知。

When to use it:

什么时候使用它:

1. When one object changes its state,then all other dependents object must automatically change their state to maintain consistency
2. When subject doesn't know about number of observers it has.
3. When an object should be able to notify other objects without knowing who objects are.

Step 1

步骤1

Create Subject class.

创建主题类。

Subject.java

Subject.java

  import java.util.ArrayList;
  import java.util.List;

  public class Subject {

  private List<Observer> observers 
        = new ArrayList<Observer>();
  private int state;

  public int getState() {
    return state;
  }

 public void setState(int state) {
   this.state = state;
   notifyAllObservers();
 }

   public void attach(Observer observer){
     observers.add(observer);       
   }

  public void notifyAllObservers(){
    for (Observer observer : observers) {
     observer.update();
  }
}   

}

}

Step 2

步骤2

Create Observer class.

创建观察者类。

Observer.java

Observer.java

public abstract class Observer {
   protected Subject subject;
   public abstract void update();
}

Step 3

步骤3

Create concrete observer classes

创建具体观察者类

BinaryObserver.java

BinaryObserver.java

public class BinaryObserver extends Observer{

  public BinaryObserver(Subject subject){
     this.subject = subject;
     this.subject.attach(this);
  }

  @Override
  public void update() {
     System.out.println( "Binary String: " 
     + Integer.toBinaryString( subject.getState() ) ); 
  }

}

}

OctalObserver.java

OctalObserver.java

public class OctalObserver extends Observer{

   public OctalObserver(Subject subject){
     this.subject = subject;
    this.subject.attach(this);
 }

  @Override
  public void update() {
    System.out.println( "Octal String: " 
    + Integer.toOctalString( subject.getState() ) ); 
  }

}

}

HexaObserver.java

HexaObserver.java

public class HexaObserver extends Observer{

  public HexaObserver(Subject subject){
    this.subject = subject;
    this.subject.attach(this);
 }

  @Override
  public void update() {
     System.out.println( "Hex String: " 
    + Integer.toHexString( subject.getState() ).toUpperCase() ); 
}

}

}

Step 4

步骤4

Use Subject and concrete observer objects.

使用主体和具体的观察者对象。

ObserverPatternDemo.java

ObserverPatternDemo.java

 public class ObserverPatternDemo {
    public static void main(String[] args) {
       Subject subject = new Subject();

       new HexaObserver(subject);
       new OctalObserver(subject);
       new BinaryObserver(subject);

       System.out.println("First state change: 15");    
       subject.setState(15);
       System.out.println("Second state change: 10");   
       subject.setState(10);
 }

}

}

Step 5

步骤5

Verify the output.

验证输出。

First state change: 15

第一个状态变化:15

Hex String: F

十六进制字符串:F

Octal String: 17

八进制字符串:17

Binary String: 1111

二进制串:1111

Second state change: 10

第二种状态变化:10

Hex String: A

十六进制字符串:

Octal String: 12

八进制字符串:12

Binary String: 1010

二进制串:1010

#4


9  

They are parts of the Observer design pattern. Usually one or more obervers get informed about changes in one observable. It's a notifcation that "something" happened, where you as a programmer can define what "something" means.

它们是观察者设计模式的一部分。通常一个或更多的obervers会被告知一个可观察到的变化。这是一个通知,“某事”发生了,你作为一个程序员可以定义什么是“某事”的意思。

When using this pattern, you decouple the both entities from each another - the observers become pluggable.

当使用这个模式时,您可以将两个实体彼此分离——观察者变成可插入的。

#5


8  

Observer a.k.a callback is registered at Observable.

观察者a.k.。回调在可观察的地方注册。

It is used for informing e.g. about events that happened at some point of time. It is widely used in Swing, Ajax, GWT for dispatching operations on e.g. UI events (button clicks, textfields changed etc).

它被用来告知某事在某一时刻发生的事情。它广泛应用于Swing、Ajax、GWT等中,用于调度UI事件(按钮单击、文本字段更改等)的操作。

In Swing you find methods like addXXXListener(Listener l), in GWT you have (Async)callbacks.

在Swing中可以找到addXXXListener(侦听器l)之类的方法,在GWT中可以找到异步回调。

As list of observers is dynamic, observers can register and unregister during runtime. It is also a good way do decouple observable from observers, as interfaces are used.

由于观察者列表是动态的,观察者可以在运行时注册和注销。这也是一种很好的方法,可以将观察到的数据与观察者分离,因为使用了接口。

#6


6  

If the interviewer asks to implement Observer design pattern without using Observer classes and interfaces, you can use the following simple example!

如果面试官要求不使用观察者类和接口实现观察者设计模式,您可以使用以下简单的示例!

MyObserver as observer interface

interface MyObserver {

    void update(MyObservable o, Object arg);
}

MyObservable as Observable class

class MyObservable
{
    ArrayList<MyObserver> myObserverList = new ArrayList<MyObserver>();

    boolean changeFlag = false;

    public void notifyObservers(Object o)
    {
        if (hasChanged())
        {
            for(MyObserver mo : myObserverList) {
                mo.update(this, o);
            }
            clearChanged();
        }
    }


    public void addObserver(MyObserver o) {
        myObserverList.add(o);        
    }

    public void setChanged() {
        changeFlag = true;
    }

    public boolean hasChanged() {
        return changeFlag;
    }

    protected void clearChanged() {
        changeFlag = false;
    }

    // ...
}

Your example with MyObserver and MyObservable!

class MessageBoard extends MyObservable {
  private String message;

  public String getMessage() {
    return message;
  }

  public void changeMessage(String message) {
    this.message = message;
    setChanged();
    notifyObservers(message);
  }

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

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

#7


4  

"I tried to figure out, why exactly we need Observer and Observable"

"我试图弄明白,为什么我们需要观察者和可观察的"

As previous answers already stated, they provide means of subscribing an observer to receive automatic notifications of an observable.

如前所述,它们提供了订阅观察者以接收可观察的自动通知的方法。

One example application where this may be useful is in data binding, let's say you have some UI that edits some data, and you want the UI to react when the data is updated, you can make your data observable, and subscribe your UI components to the data

一个可能有用的示例应用程序是数据绑定,假设您有一些UI来编辑一些数据,并且您希望UI在数据更新时发生响应,您可以使您的数据可观察,并将您的UI组件订阅到数据。

Knockout.js is a MVVM javascript framework that has a great getting started tutorial, to see more observables in action I really recommend going through the tutorial. http://learn.knockoutjs.com/

淘汰赛。js是一个MVVM javascript框架,它有一个很好的入门教程,要查看更多的可观察的内容,我建议您阅读本教程。http://learn.knockoutjs.com/

I also found this article in Visual Studio 2008 start page (The Observer Pattern is the foundation of Model View Controller (MVC) development) http://visualstudiomagazine.com/articles/2013/08/14/the-observer-pattern-in-net.aspx

我还在Visual Studio 2008 start页面(Observer模式是Model View Controller (MVC)开发的基础)http://visualstudiomagazine.com/articles/2013/3/08/14 / The - Observer - Pattern -in-net.aspx上发现了这篇文章

#8


2  

I have written a short description of the observer pattern here: http://www.devcodenote.com/2015/04/design-patterns-observer-pattern.html

我在这里写了一个关于观察者模式的简短描述:http://www.devco去记/2015/04/design-patterns-observer-pattern.html

A snippet from the post:

文章片段:

Observer Pattern : It essentially establishes a one-to-many relationship between objects and has a loosely coupled design between interdependent objects.

观察者模式:它在对象之间建立一个一对多的关系,在相互依赖的对象之间建立一个松散耦合的设计。

TextBook Definition: The Observer Pattern defines a one-to-many dependency between objects so that when one object changes state, all of its dependents are notified and updated automatically.

教科书定义:观察者模式定义了对象之间的一对多依赖关系,因此当一个对象改变状态时,它的所有依赖关系都会被自动通知和更新。

Consider a feed notification service for example. Subscription models are the best to understand the observer pattern.

例如,考虑一个提要通知服务。订阅模型是理解观察者模式的最佳方式。

#9


0  

Observer pattern is used when there is one-to-many relationship between objects such as if one object is modified, its dependent objects are to be notified automatically.

当对象之间存在一对多关系时(例如,如果一个对象被修改,那么它的相关对象将被自动通知),则使用Observer模式。

#10


0  

Since Java9, both interfaces are deprecated, meaning you should not use them anymore. See Observer is deprecated in Java 9. What should we use instead of it?

由于Java9,这两个接口都被废弃了,这意味着您不应该再使用它们了。在Java 9中不赞成使用Observer。我们应该用什么来代替它呢?

However, you might still get interview questions about them...

然而,你可能仍然会收到关于他们的面试问题……