寻找UI的命令模式示例
我正在使用基本UI来开发WinForm .Net应用程序,该UI包括工具栏按钮,菜单项和击键,它们均启动相同的基础代码。现在,每个事件处理程序都调用一个通用方法来执行该功能。
从我所读的内容中,可以通过Command设计模式来处理这种类型的操作,其额外好处是可以自动启用/禁用或者选中/取消选中UI元素。
我一直在网上搜索一个很好的示例项目,但实际上还没有找到一个。有没有人有可以分享的好榜样?
解决方案
回答
尝试使用开源的.NET编辑器,例如SharpDevelop或者Notepad ++。
(自然地)在http://c2.com/cgi/wiki?CommandPattern上对命令模式进行了一些讨论可能会有所帮助。
回答
首先确保我们知道什么是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.
这是给你的例子。我们可以通过多种方法来执行此操作,但是我将采用基于接口的方法来使代码更可测试。我不确定我们喜欢哪种语言,但我是用C#编写的。
首先,创建一个描述命令的界面。
public interface ICommand { void Execute(); }
其次,创建将实现命令接口的命令对象。
public class CutCommand : ICommand { public void Execute() { // Put code you like to execute when the CutCommand.Execute method is called. } }
第三,我们需要设置我们的调用者或者发送者对象。
public class TextOperations { public void Invoke(ICommand command) { command.Execute(); } }
第四,创建将使用调用者/发送者对象的客户端对象。
public class Client { static void Main() { TextOperations textOperations = new TextOperations(); textOperation.Invoke(new CutCommand()); } }
我希望我们可以使用此示例并将其用于我们正在处理的应用程序。如果我们想进一步澄清,请告诉我。
回答
我们走对了。基本上,我们将有一个代表文档的模型。我们将在CutCommand中使用此模型。我们将需要更改CutCommand的构造函数以接受要剪切的信息。然后每次,例如说单击"剪切按钮",便调用一个新的CutCommand并将参数传递给构造函数。然后在调用Execute方法时在类中使用这些参数。
回答
Qt将命令模式用于菜单栏/工具栏项。
QAction是与QMenuItem和QToolbar分开创建的,可以分别使用setAction()和addAction()方法将这些Action分配给QMenuItem和QToolbar。
http://web.archive.org/web/20100801023349/http://cartan.cas.suffolk.edu/oopdocbook/html/menus.html
http://web.archive.org/web/20100729211835/http://cartan.cas.suffolk.edu/oopdocbook/html/actions.html