命令模式:按顺序执行多个命令
我想发出一系列命令执行,但前提是前一个命令成功。现在我正在命令对象中引发一个事件,指示命令是成功还是失败。我用它来控制执行,但感觉不优雅。
示例:
command1.CommandSucceeded += delegate { command2.Execute(); };
command1.Execute();
这可行,但感觉笨拙且不直观。我可以在 Execute() 上传递一个布尔值来指示成功或失败,但这是沿着相同的路径。我可以在失败时抛出异常,这可能会导致代码更清晰,但可能有点过头了。
有什么建议吗?
I want to issue a series of Command executions, but only when the prior command succeeded. Right now i am raising an event within the command object indicating whether the command succeeded or failed. I am using this to control execution, but it feels inelegant.
Example:
command1.CommandSucceeded += delegate { command2.Execute(); };
command1.Execute();
This works, but it feels clumsy and unintuitive. I could pass a boolean back on Execute() indicating success or failure, but that is along the same path. I could throw exceptions on failure, which would might result in cleaner code, but might be overkill.
Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我通过设置命令“链”解决了这个问题。我创建了一个 Command 对象来保存其他命令,然后在调用 Do 时依次触发每个命令。在您的情况下,您可以让命令调用委托,并且仅在成功时才触发序列中的下一个命令。
我想这是一种方法。
I got around this by setting up a command "chain". I created a Command object that holds other commands, then fire each of them in turn when Do is called. In your case, you could have the command call the delegate and only fire off the next command in the sequence if it was successful.
One way to do it, I suppose.
返回一个布尔值或代表某种状态的对象并不是那么糟糕。可能会感觉笨拙,但它简单明了。
我使用的一个实现是这样的:
首先,我将 Command 对象添加到列表中。
然后 Command 对象列表将像这样执行:
Returning a boolean or an object representing some status is not that bad. It might be feel clumsy, but it's simple and clear.
One implementation I use is something like this:
First I add the Command objects into a list.
Then the list of Command objects gets executed like this: