简体   繁体   English

观察者如何订阅可观察物?

[英]How observers subscribe on observables?

I have read a book named "Head First Pattern" and have a question about pattern "Observer". 我已经读过一本名为《 Head First Pattern》的书,并且对“ Observer”模式有疑问。

How should an observer subscribe on observable if it's API include only 1 method "update()"? 如果观察者的API仅包含1个方法“ update()”,那么观察者应如何订阅它呢?

Firstly, I assume that observer it must contain method "subscribe(Observable observable)" 首先,我假设观察者必须包含方法“ subscribe(Observable observable)”

How to implement a mechanism of subscription in the best way? 如何以最佳方式实施订阅机制?

Actually, it's the other way around. 实际上,这是另一回事。 You attach or add an Observer to an object that will be observed, an Observable . 您将Observer附加或添加到将被观察的对象Observable You do that so that the observed object is able to notify the observers once its state has changed. 这样做是为了使观察到的对象一旦状态改变就能够notify观察者。

In this pattern, if you were to subscribe a Subject in an observer object and only do that. 在这种模式中,如果您要在观察者对象中订阅Subject ,则只能这样做。 How could the observer know when the subject's state was changed the moment the action took place? 观察者如何知道行为发生时对象的状态何时发生变化? Maybe the observer could start polling and asking about the subject's state until it changes and then the observer would act on it. 也许观察者可以开始轮询并询问对象的状态,直到状态改变为止,然后观察者将对此采取行动。 But that is far from ideal. 但这远非理想。

That is kind of what happens with a WatchService in which you, for instance, add a file to a service in order to be notified once the file is modified. 这就是WatchService所发生的情况,例如,您在其中将文件添加到服务中以便在文件被修改后得到通知。 Roughly, you're "subscribing" the subject in the observer. 大致来说,您是在观察者中“订阅”主题。 But here, you start a service that will take care of what you need behind the curtains. 但是,在这里,您将启动一项服务,该服务将照顾您的幕后需求。

Anyway, in your case, the best way would be to let the subject object manage the observers and call it whenever is appropriate. 无论如何,在您的情况下,最好的方法是让主题对象管理观察者并在适当的时候调用它。

Check out this link: https://sourcemaking.com/design_patterns/observer 查看此链接: https : //sourcemaking.com/design_patterns/observer

You must implement your class Subject so that it receives entities that will observe its behavior and be notified as desired. 您必须实现您的Subject类,以便它接收将观察其行为并根据需要通知的实体。 It's the Subject's duty to notify the observers when a desired change has been made. 当进行了所需的更改时, Subject's责任notify观察者。

Java has its own implementation of the pattern. Java有其自己的模式实现。 You should start by reading the Observable class to get the gist of it. 您应该先阅读Observable类以获取要点。 Then, you should implement your own following the guidelines you've read. 然后,您应该按照已阅读的指南实施自己的指南。 The idea is like this: 这个想法是这样的:

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

public class TestObserver {
    public static void main(String[] args) {
        Subject subject = new Subject();
        ContentObserver contentObs = new ContentObserver();
        subject.addObserver(contentObs);
        // Once you call setContent, the object contentObs
        // will be notified and print the desired text
        subject.setContent("test");
    }
}

class Subject {

    private String content;

    private List<ContentObserver> observers = new ArrayList<>();

    public void addObserver(ContentObserver obs) {
        observers.add(obs);
    }

    public void setContent(String content) {
        this.content = content;
        notifyContentObservers();
    }

    private void notifyContentObservers() {
        observers.forEach(obs -> obs.update(content));
    }

}

class ContentObserver {

    public void update(String content) {
        System.out.println("Content was changed! New content = " + content);
    }

}

Remember that this is an example. 请记住,这是一个示例。 You must manage your observers by adding, removing, etc. It's also advisable to code to an interface , so you should create your own Observer interface according to what you want to observe. 您必须通过添加,删除等方式来管理观察者。也建议对接口进行编码 ,因此您应该根据要观察的内容创建自己的Observer接口。

Also, you shouldn't use the implementation provided by java as it's deprecated in java 9: https://docs.oracle.com/javase/9/docs/api/java/util/Observable.html https://dzone.com/articles/javas-observer-and-observable-are-deprecated-in-jd 此外,你不应该使用Java提供的实现,因为它在Java 9弃用: https://docs.oracle.com/javase/9​​/docs/api/java/util/Observable.html https://开头dzone。 COM /用品/ Java类观察者和观察的,被弃用,在-JD

If you want something more reliable and reactive. 如果您想要更可靠和反应更快的产品。 Take a look at: https://docs.oracle.com/javase/9/docs/api/java/util/concurrent/Flow.html 看看: https : //docs.oracle.com/javase/9​​/docs/api/java/util/concurrent/Flow.html

Cheers! 干杯!

 observable.addObserver(observer);
 // now when observable changes, the observer will know

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM