耦合观察者与主题 [英] Coupling observer with subject

查看:112
本文介绍了耦合观察者与主题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在观察者设计模式中,我知道我们必须向观察者注册该主题。但是我注意到,在某些实现中,主体实例通过观察器类发送,然后观察者的对象使用主体的实例发送到Subject类。见下面的例子

In the observer design pattern I know we have to register the observer with the subject. But i have noticed that in some implementations the subject instance is send through the observer class and then the object of observer is send to Subject class using the instance of subject. See the example below

public class Observer1 extends Observer {

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

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

我的问题是Observer类是否需要主体实例?我认为观察者完全脱离主题

My question is does the Observer class need to have the subject instance? I thought Observer was totally decoupled from the subject

有人可以给我一个很好的执行观察者设计模式或任何资源

Could someone give me a good implementation of Observer design pattern or any resources

推荐答案

观察者在观察者通常不会将Observable对象(您称之为主题)的引用保留在字段中,因为Observer通常已经将Observable对象作为更新方法的参数。

Theoretically the Observer does not need to keep the reference of the Observable object (what you call 'Subject') in a field, since the Observer normally already receive the Observable object as a parameter of the update method.

这篇关于耦合观察者与主题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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