观察者模式如何以及为何实现了MVC架构风格?

huangapple go评论119阅读模式
英文:

How and why can the Observer Pattern implement the MVC Architectural Style?

问题

我想更好地理解观察者模式如何用于实现MVC架构。您能解释这如何工作吗?如果可能的话,附带一个示例,并为每个组件指定其角色?

英文:

I would like to understand better how and why the observer pattern can be used to implement an MVC architecture. Can you explain how this could work, if possible with an example, and specify for each component its role?

答案1

得分: 1

你会在《设计模式:可重用面向对象软件的元素》1一书中找到详细的答案。在其中一个介绍性章节中,他们将MVC分解为他们的几种设计模式的组合。

MVC中,你有:

  • 一个模型,带有领域对象
  • 一个控制器,负责处理用户输入
  • 一个或多个视图,向用户显示模型的数据。

视图可以查询模型,但模型也可以通知视图发生了某些变化。这通常是使用观察者模式来实现的:

  • 模型是被观察的主体
  • 视图是订阅模型的观察者
  • 当模型更改时,它通知视图发生了变化。然后视图可以查询已更改的数据并刷新向用户显示的内容。

如果你想深入了解,你可能会对这个视频感兴趣。讲师提供了一些课程材料的链接,如果你更喜欢阅读而不是观看。

英文:

You'll find a detailed answer in Design Patterns: Elements of Reusable Object-Oriented Software. In one of the introductory chapter they decompose MVC into a combination of several of their design patterns.

In MVC, you have:

  • A model, with the domain objects
  • One controler, that takes care of the user input`
  • One or several views, that show data of the model to the user.

A view may query the model, but a model may also inform views that some change took place. This is typically implemented with the observer pattern:

  • the model is the observed subject
  • the view is an observer that subscribes to the model
  • when the model changes, it notifies the view that a change took place. The view can then query for changed data and refresh what's shown to the user.

If you want to dive deeper, you may be interested in this video. The instructor provides a link to some course material, if you prefer to read than to look.

huangapple
  • 本文由 发表于 2020年6月29日 15:09:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/62632932.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定