简体   繁体   English

如何在Java中实现与观察者模式相反的方式?

[英]How to implement contrary to observer pattern in java?

In observer pattern Observer notifies listeners usually by invoking on each some method like: 在观察者模式中,观察者通常通过调用每种方法来通知侦听器,例如:

OnSomethingUpdated(Object) {
....

In this case we have coupling: Observer should do some operation with each listener. 在这种情况下,我们具有耦合:观察者应对每个侦听器执行一些操作。 When I would like modify Observer or Listener by inheritance or try to extract abstract superclass for simplify logic of Observer (or Listener) it getting difficult propagate messages, I receive spaghetti code. 当我想通过继承修改Observer或Listener或尝试提取抽象超类以简化Observer(或Listener)的逻辑时,传播消息变得越来越困难,我收到了意大利面条式代码。 I think that should exists some way of decoupling business logic of work of Observer from logic of propagating messages to listeners. 我认为应该存在某种将Observer的业务逻辑与将消息传播给侦听器的逻辑分离的方式。 May be better contrary - listeners should check some pool of messages. 可能相反,监听器应该检查一些消息池。 Does exist similar pattern? 是否存在类似的模式? Thanks. 谢谢。

The listener should actually be an interface: 侦听器实际上应该是一个接口:

interface MyListener {
  void onSomethingUpdated(Object eventData);
}

This way, the subject is decoupled from the concrete instances of its observers; 这样,主题便脱离了其观察者的具体实例。 It should keep a list of these interface references. 它应该保留这些接口引用的列表。

Take a look here for how to implement this pattern in Java. 在这里看看如何在Java中实现此模式。

Now, to further decouple the subject from the message propagation, I suggest you take a look at the mediator pattern. 现在,为了进一步使主题与消息传播脱钩,建议您看一下中介模式。

In the observer pattern , an Observer registers with an Observable subject. 观察者模式中ObserverObservable对象注册 The onSomethingUpdated() method of the Observer is invoked by the Observable , which notifies all loosely-coupled listeners. ObserveronSomethingUpdated()方法由Observable调用,该方法通知所有松耦合的侦听器。 There's a related example here . 有一个相关的例子在这里

观察者模式

You're probably not going to like this answer very much, but I'll say it anyway: inheritance is not for code reuse. 您可能不太会喜欢这个答案,但是无论如何我都会说: 继承不是为了代码重用。 The observer pattern should not lead to tight coupling -- it should lead to decoupling! 观察者模式不应该导致紧密耦合-它应该导致去耦! So if you're ending up with spaghetti code around your observers/listeners when you're extracting abstract base classes or subclassing, it's because you shouldn't be using inheritance. 因此,如果在提取抽象基类或子类时以观察者/侦听器结尾的意大利面条代码结尾,那是因为您不应该使用继承。

There, I said it. 在那里,我说了。

You could add a Business Delegate in between or a simple Facade. 您可以在两者之间添加一个业务代表 ,也可以添加一个简单的Facade。

So the Observer will only receive the Notification and then delegate the implementation to actual object that contains the Business Logic. 因此,观察者将仅接收通知,然后将实现委派给包含业务逻辑的实际对象。 This way you are free to make changes to your Business Logic class as you like. 这样,您就可以随意更改您的业务逻辑类。

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

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