观察者模式与事件驱动方法之间的区别 [英] Difference between Observer Pattern and Event-Driven Approach

查看:439
本文介绍了观察者模式与事件驱动方法之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我总是发现观察者模式几乎与通常的事件驱动方法相似.实际上,我几乎相信它们实际上是指同一事物的不同名称.它们都使用相似的概念作为侦听器,甚至在实现中,它们几乎是同一件事,那就是具有回调方法/函数来执行操作.至少在Java中是这样.

I always found the Observer Pattern almost similar to the usual event-driven approach. Actually, I have almost believed that they are actually just different names referring to the same thing. They both use similar concepts to have something as a listener and even in the implementation, they are almost the same thing, that's to have a callback method/function to carry out an action. This is at least in Java.

用其他语言(如Actionscript/Flex)说,事件更加用户友好,并且看起来似乎不仅仅是观察者模式定义的事情.但是,这些概念听起来还是一样.

In other languages say Actionscript/Flex, the events are more user-friendly and may look like it does more than just the observer pattern defines. But still, the concepts sound the same.

但这是真的吗?观察者模式与通常的事件驱动编程风格一样吗?

But is this really true? Is the Observer Pattern the same thing as the usual event-driven programming style?

推荐答案

观察者模式是一个非常特殊的实例.事件驱动可能意味着任何事情.在大多数观察者模式实现中,观察者是监视观察者的对象.当观察者发生变化时,将调用观察者的方法.严格来说,这不是事件".这意味着:对观察者的各种不同动作通常会导致观察者中不同方法的调用.该方法改变了语义什么". 在事件驱动系统中,您基本上有一个使用对象/方法,并且该消息说明事件中发生了更改或发生了什么.那可以是任何东西,而不仅限于观察某些东西的想法!这意味着:在事件驱动系统中,您可以通过添加新的事件类型来获得新的语义.在观察者模式中,通常通过向Observer类添加方法来添加语义.但是,没有人阻止您将Observer实施为ChangeEvent的特殊侦听器.

The Observer Pattern is a very special instance. Event-Driven can mean anything. In most Observer Pattern implementations the Observer is an object watching the observee. When the observee is changed, a method of the observer is called. Strictly speaking this is not an "Event". That means: various different actions on the observee, usually lead to the call of different methods in the observer. The semantics "what" got changed is in the method. In Event Driven Systems, you basically have one consuming object/method and the message what was changed or what happend is in the Event. That can be anything and is not limitd to the idea of observing something! That means: in an Event Driven System you get new semantics by adding new Event types. In an Observer Pattern you usually add semantics by adding a method to the Observer class. HOWEVER: no one is preventing you to implement an Observer as a special listern to ChangeEvents.

这篇关于观察者模式与事件驱动方法之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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