简体   繁体   English

我可以申请哪种设计模式来处理命令?

[英]Which design pattern can I apply for handling command application?

If I have an application of handling commands and processing, is there a suitable design pattern should I use because currently I have a long switch case statements? 如果我有处理命令和处理的应用程序,由于当前我有很长的switch case语句,应该使用合适的设计模式吗?

switch(command)

{
   case ACK : // process(); break;
   case NAK : // process(); break;
   case POLL: // process(); break;
   ...
}

You could definitely do a few things here. 您绝对可以在这里做一些事情。 If it's really as simple as tying a command to a value, you can use a simple Dictionary to tie a command name to a delegate that it executes, like: 如果将命令绑定到值真的那么简单,则可以使用简单的Dictionary将命令名称绑定到执行的委托,例如:

private static IDictionary<string, Action> _actionsByCommand;

static MyClass() {
    _actionsByCommand[ACK] = Acknowledge;
    _actionsByCommand[POLL] = Poll;
}

private static void Acknowledge() { }
private static void Poll() { }

static void Main() {
    string command = ...;
    _actionsByCommand[command]();
}

Or instead of delegates, you can define classes for each of your commands with a shared base class or interface, and have a Go method of some kind that executes. 或代替委托,您可以使用共享的基类或接口为每个命令定义类,并具有执行的某种Go方法。 This would give you the benefit of having additional properties or values tied to each command, if you need it down the road. 如果您需要在每个命令中添加附加属性或值,这将为您带来好处。

Lets say you have three methods with the same signature. 假设您有三种具有相同签名的方法。

public Func<string, int> Ack = (i) => return 1;
public Func<string, int> Nack= (i) => return 1; 
public Func<string, int> Poll = (i) => return 1; 

and you want to call them without case statement. 而您想不带案例说明就打电话给他们。

public int Call(string commandName)
{
    //Find method
    var method = this.GetType().GetFields().First(x=>x.Name == commandName);
    if (method == null) return null;
    //Convert it to Func
    var m = (Func<string, int>) method.GetValue(this);
    return m.Invoke("");
}

you will use it like. 您将像使用它。

new MethodRunner().Call("Ack");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM