窗户形式和设计模式

时间:2011-03-21 18:13:22

标签: c# design-patterns

我比较熟悉mvc,mvp或mvvm模式。所以我正在搜索谷歌为win form应用程序实现良好的设计模式。我找到了很多文章。很多人说mvc很好,很少有人说mvp非常适合赢取应用程序。我找到了一个非常小的代码,在win应用程序中实现了mvp。我查看代码,发现开发人员必须编写大量额外的代码来绑定treeview或任何控件。

代码如下

public interface IYourView
{
   void BindTree(Model model);
}

public class YourView : System.Windows.Forms, IYourView
{
   private Presenter presenter;

   public YourView()
   {
      presenter = new YourPresenter(this);
   }

   public override OnLoad()
   {
         presenter.OnLoad();
   }

   public void BindTree(Model model)
   {
       // Binding logic goes here....
   }
}

public class YourPresenter
{
   private IYourView view;

   public YourPresenter(IYourView view)
   { 
       this.view = view;
   }

   public void OnLoad()
   {
       // Get data from service.... or whatever soruce
       Model model = service.GetData(...);
       view.BindTree(model);
   }
}

请有人通过代码并帮助我理解流程,因为代码应该用mvp模式编写,我不知道。感谢。

1 个答案:

答案 0 :(得分:2)

此代码已使用MVP模式。

它声明了一个接口IYourView和一个实现System.Windows.Form和这个新接口的具体类YourView。基本上,正在做的是创建一个新表单,并增加了它还实现BindTree()中定义的IYourView方法的要求。

然后YourView类(表单)具有YourPresenter的依赖关系,以便将OnLoad事件与演示者挂钩,尽管我会在演示者订阅的地方执行此操作而是表单的OnLoad事件。

演示者YourPresenter将YouView的一个实例作为依赖项,然后它可以在其余逻辑中使用该实例。

现在,要使用它,您将遵循类似于此的过程:

  • 创建YourView的新实例(然后依次创建演示者)
  • 在演示者中实现逻辑(即创建GetModel())以创建要绑定到树的模型
  • 在演示者中调用view.BindTree(model),其中模型是您刚才在上一步中创建的内容

因此,创建一个视图实例:

IYourView newView = new YourView();

然后在您的演示者课程中:

Model model = GetModel();
newView.BindTree(model);