1

我有两个类和一个用户窗体。我试图不在我的课程中使用任何与表单相关的代码,但我对 OOP 还是很陌生。在 CreateGraph() 方法中,我想用是/否对话框提示用户。该方法中的代码将根据结果继续执行。我已经阅读了一些关于 MVP 的示例,但不确定在这种情况下如何实现。

有人可以指导我吗?我确实相信我的代码中存在一些严重的设计问题

//singleton class
public class MyApplication
{
    private int state;
    private static MyApplication instance = null;

    public void Task1()
    {
        GraphGenerator gg = new GraphGenerator();
        gg.CreateGraph();
        state = 1;
    }

    public void Task2()
    {
        //some other tasks..
        state = 2;

    }
}

我有问题的班级..

public class GraphGenerator
{
    public void CreateGraph()
    {
        //some code for creating a graph..
        //here i want to prompt the user with a
        // Yes/No dialog box..
    }
}

用户表单

public partial class Form1 : Form
{
    private void btnTask1_Click(object sender, EventArgs e)
    {
        MyApplication ma = MyApplication.Instance;
        ma.Task1();
    }

    private void btnTask1_Click(object sender, EventArgs e)
    {
        MyApplication ma = MyApplication.Instance;
        ma.Task2();
    }
}
4

3 回答 3

2
  1. 命名 - MyApplication - 是控制器或演示者的错误名称,例如使用“表单名称”+“演示者”进行命名。
  2. 辛格尔顿。控制器或演示者不应是单例的。通过构造函数注入它或在 ctor 中创建,然后使用类中的私有 setter 保存到字段或属性。例如:

    public Form1(FormPresenter presenter)
    {
       InitializeComponent();
       this.presenter = presenter;
    }
    
  3. 这个简单样本上的所有其他内容都是正常的。但是对于按钮事件处理程序,您可以在演示者/控制器中使用事件,并在特定于演示者/控制器事件的​​按钮事件处理程序中触发。

也尝试寻找 MVC/MVP 框架。在此处查找相关问题: Implementing MVC with Windows Forms

我记得有 Microsoft Smart Client Guidance (CAB / Microsoft Composite Application Block)

于 2012-06-18T08:40:36.350 回答
1

First , it is best to design your classes as much as possible such that you don't need to intermingle UI code with your domain objects. Can you restructure the code so that the caller/owner of GraphGenerator decides if it needs to ask the user something instead of GraphGenerator doing it? Try to keep GraphGenerator solely focused on his task or making graphs.

Failing that, you could define events (or delegates or callback interface, but lets call these related mechanisms events for now) within GraphGenerator such that the caller/owner can listen for notifications from GraphGenerator and in turn interact with the user. For example, define an event called QueryConfirmSave to raise and the caller can handle the event and prompt the user and then pass back a boolean as an EventArg field.

(The code would be something like this (from the hip, not editor checked):

GraphGenerator gg = new GraphGenerator();
gg.QueryConfirmSave += new EventHandler<ConfirmSaveArgs>(GraphGenerator_QueryConfirmSave);

and then:

private void GraphGenerator_QueryConfirmSave(object sender, ConfirmSaveArgs args)
{
   if (MessageBox.Show("Save?") == DialogResult.Yes)
   {
      args.SaveConfirmed = true;
   }
}
于 2012-06-18T13:31:20.757 回答
-3

你需要MessageBox.Show(...)

于 2012-06-18T08:36:49.493 回答