java - 观察者模式 vs 事件总线消息方法

标签 java oop model-view-controller design-patterns architecture

我一直在密切关注 MVC 实现和事件总线。

为什么不使用 Event-bus 而不是 Observer Pattern 来实现 MVC 应用程序?

例如,假设我有两个类 ModelView , 在典型的观察者模式中,它将是:

public class Model implements Subject { ... }

public class View implements Observer { ... }

相反,使用 green robot event bus 的方法的好处/缺点是什么?或任何其他事件总线?

它会是这样的:
public class Model {
   private int field = 0; 

   void someFunctionNowTriggerStateChange() {
     this.field = field + 1;
     ...EventBus.getDefault().post(this); //pass itself as the event
   }
}

public class View {

  @Subscribe onModelUpdated(Model model) {
    updateTextLabel(model);
    //other model updates
  }   
}

与典型的观察者相比,使用 EventBus 实现 MVC 有哪些问题(如果有)?

最佳答案

EventBus 实现了发布者订阅者模式,

EventBus is an open-source library for Android and Java using the publisher/subscriber pattern for loose coupling.



difference from observer pattern是出版商是松散耦合 来自订阅者

publisher and subscriber don’t know about the existence of one another. There is a third component, called broker or message broker or event bus, which is known by both the publisher and subscriber, which filters all incoming messages and distributes them accordingly. In other words, pub-sub is a pattern used to communicate messages between different system components without these components knowing anything about each other’s identity.



一个优点是发布者/订阅者模式可以正常/更容易地以异步方式实现,因为有第三个组件,代理,帮助实现异步行为,因为执行变得松散耦合

另一个优点,因为发布者/订阅者模式是松散耦合的,实现多个订阅者会更直观/更容易

Observer pattern is mostly implemented in a synchronous way, i.e. the Subject calls the appropriate method of all its observers when some event occurs. The Publisher/Subscriber pattern is mostly implemented in an asynchronous way (using message queue).



如果你不需要(也不会需要)这样的代理,你可以安全地使用观察者模式,这将使你的代码更小更简单

关于java - 观察者模式 vs 事件总线消息方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57024456/

相关文章:

java - 从时间选择器获取时间值 - android

Java 循环 - 不断请求用户输入

javascript - 如果今天是会计年度的最后一天,则从下拉菜单中删除当前年份

c++ - 缓存单个重写计算 C++11

java - 在 while 表达式中初始化变量 - 而不是语句

java - 我应该总是使用静态工厂方法而不是构造函数吗?

java - 为什么 Logger 大部分时间是静态的?

objective-c - 每个 .swift 文件不应该是一个类吗?

java - 在 JavaFX 中使用 UI 显示和创建枚举的最佳实践是什么?

java - Spring Boot 可以设置从 Controller 端点下载的文件的名称吗?