Is the observer object oriented design pattern just a form of implementing a callback?

萝らか妹 提交于 2021-01-29 11:07:17

问题


I was recently asked what is the difference between a callback and an observer in the Observer OO design pattern. My understanding is that callback is any executable code passed as an argument to a function which is called when a specific event happens. It may be implemented in different forms in different programming languages, such as function pointers, anonymous functions and observers/listeners in the object-oriented paradigm.

Developers usually implement callback registration synchronously with code execution and support only one callback, while observers/listeners callback registration is always asynchronous with code execution and multiple registration is supported.

However, I believe that those usual limitations of sync and cardinality in a callback are not inherent in its definition. Is that right?

Reference: https://en.wikipedia.org/wiki/Callback_(computer_programming)


回答1:


I don't know that there is any official definition of callback. At least, it doesn't show up in SE Vocab. It does show up on SO, but you can see some variation in the answers.

Observer does have an official definition (GoF) and it is synonymous with publish/subscribe. Surely there are developers who define callback broadly enough to encompass pub/sub. Others draw a distinction between the two.

You have to choose a callback definition. Then you will have an answer to this question.

By the way, regarding Wikipedia, there is extremely inaccurate and misleading information on numerous design patterns there; so I would in no way consider it an official definition for anything technical.



来源:https://stackoverflow.com/questions/58841976/is-the-observer-object-oriented-design-pattern-just-a-form-of-implementing-a-cal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!