Looking for example of Command pattern for UI(寻找 UI 的命令模式示例)
问题描述
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.
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 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.
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();
}
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.
这篇关于寻找 UI 的命令模式示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:寻找 UI 的命令模式示例
基础教程推荐
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
