公开方法或订阅View事件 [英] Public Methods or subscribe to View events

查看:48
本文介绍了公开方法或订阅View事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个MVP项目,其中View是一个实现IView接口的WinForm. 我正在审查代码,在可能的地方进行改进,并想问您关于视图和演示者如何交互的想法.您认为以下哪项是最佳做法?

I have written a MVP project where the View is a WinForm that implements my IView interface. I am in the process of reviewing the code, improving it where I can and would like to ask your thoughts regarding how the view and presenter interact. Which of the following is best practice in your opinion?

  1. 公开演示者类的方法供视图使用. (即将其公开).
  2. 让演示者收听View类引发的事件.

例如,我的MVP使用通过串行端口进行通信的服务.要连接到远程设备,我的视图调用了公共Presenter方法Connect(),然后调用了相应的服务方法.

For example, my MVP uses a service that communicates via a serialport. To connect to the remote device my view calls the public Presenter method Connect() which then calls the appropriate service methods.

更好的做法是引发Connect()事件并让主持人收听吗?

Would it be better practice to raise a Connect() event and have the presenter listen for it?

推荐答案

一般来说,我的工作是使视图取决于演示者,而演示者取决于模型.这意味着可以由多个演示者使用同一模型,并且可以在我的多个视图中使用同一演示者(不同的UI布局,或者Winforms vs Web等).为方便起见,该视图在演示者上调用公共方法,并侦听演示者的事件以说出数据已更改的时间.

Generally I work so that the view is dependant on the presenter and the presenter is dependant on the model. This means the same model can be used by multiple presenters and the same presenter can be used my multiple views (different UI layouts, or Winforms vs Web etc). To facilitate this the view calls public methods on the presenter and listens to events from the presenter to say when data has changed.

举一个为什么您可能要用这种方式工作的示例,假设一个界面有两个视图,一个视图供初学者用户使用,一个视图供专家使用,而初学者视图则显示专家命令的子集.如果这两个视图使用相同的演示者,则初学者视图将需要公开所有专家命令的事件,因为演示者需要将它们放在那里,以便可以绑定到它们,即使它们永远不会被触发.另一方面,演示者可以公开所有专家选项的方法,而初学者视图永远不会调用它们,这意味着视图和演示者都没有实现未使用的功能.

For an example of why you may want to work this way imagine an interface that has two views one for a beginner user and one for an expert, with the beginner view showing a subset of the expert commands. If the same presenter is used for both of these views then the beginner view will need to expose events for all the expert commands since the presenter needs them to be there so it can bind to them - even though they will never be triggered. On the other hand the presenter can expose methods for all of the expert options and the beginner view just never calls them, this means that neither the view nor the presenter are implementing unused functionality.

这篇关于公开方法或订阅View事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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