寻找例子的命令模式的UI例子、命令、模式、UI

2023-09-04 01:34:43 作者:莓小汐°

我工作的一个WinForm .NET应用程序的基本用户界面,包括工具栏按钮,菜单项和键盘全部启动相同的底层code。现在对于每个这些事件处理程序调用一个常用的方法以执行该功能。

I'm working on a WinForm .Net application with the basic UI that includes toolbar buttons, menu items and keystrokes that all initiate the same underlying code. Right now the event handlers for each of these call a common method to perform the function.

这是我看过这种类型的行动可以由命令设计模式来处理与附加的自动启用/禁用或选中/取消选中的UI元素的好处。

From what I've read this type of action could be handled by the Command design pattern with the additional benefit of automatically enabling/disabling or checking/unchecking the UI elements.

我一直在寻找的净一个很好的例子项目,但真的还没有找到一个。有没有人有一个很好的例子,可以共享?

I've been searching the net for a good example project, but really haven't found one. Does anyone have a good example that can be shared?

推荐答案

让我们首先要确保我们知道的命令模式是什么:

Let's first make sure we know what the Command pattern is:

Command模式封装的请求   作为一个对象,并赋予它一个已知的   公共接口。命令模式   确保每一个对象接收它的   自己的命令,并提供一个去耦   之间发送和接收。发件人   是一个对象,调用一个   操作,和一个接收器是一个目的   接收该请求,并作用在   吧。

Command pattern encapsulates a request as an object and gives it a known public interface. Command Pattern ensures that every object receives its own commands and provides a decoupling between sender and receiver. A sender is an object that invokes an operation, and a receiver is an object that receives the request and acts on it.

下面是一个例子。有很多方法可以做到这一点,但我要带一个接口的基础方法,使code更容易测试你。我不知道用什么语言你preFER,但我写在C#。

Here's an example for you. There are many ways you can do this, but I am going to take an interface base approach to make the code more testable for you. I am not sure what language you prefer, but I am writing this in C#.

首先,创建一个描述命令的接口。

First, create an interface that describes a Command.

public interface ICommand
{
    void Execute();
}

二,创建将实施命令interface命令对象。

Second, create command objects that will implement the command interface.

public class CutCommand : ICommand
{
    public void Execute()
    {
        // Put code you like to execute when the CutCommand.Execute method is called.
    }
}

第三,我们需要设置我们的调用或发件人的对象。

Third, we need to setup our invoker or sender object.

public class TextOperations
{
    public void Invoke(ICommand command)
    {
        command.Execute();
    }
}

四,创建将使用调用/发送对象的客户对象。

Fourth, create the client object that will use the invoker/sender object.

public class Client
{
    static void Main()
    {
        TextOperations textOperations = new TextOperations();
        textOperation.Invoke(new CutCommand());
    }
}

我希望你可以把这个例子并投入使用了您正在使用的应用程序。如果您想了解更多的澄清,只是让我知道。

I hope you can take this example and put it into use for the application you are working on. If you would like more clarification, just let me know.

 
精彩推荐
图片推荐