命令模式:按顺序执行多个命令

发布于 2024-08-02 13:17:09 字数 312 浏览 11 评论 0原文

我想发出一系列命令执行,但前提是前一个命令成功。现在我正在命令对象中引发一个事件,指示命令是成功还是失败。我用它来控制执行,但感觉不优雅。

示例:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

如此安好 2024-08-09 13:17:09

我通过设置命令“链”解决了这个问题。我创建了一个 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.

所有深爱都是秘密 2024-08-09 13:17:09

返回一个布尔值或代表某种状态的对象并不是那么糟糕。可能会感觉笨拙,但它简单明了。

我使用的一个实现是这样的:

首先,我将 Command 对象添加到列表中。

List<ICommand> commands = new List<ICommand>;
commands.Add(command1);
commands.Add(command2);

然后 Command 对象列表将像这样执行:

foreach (ICommand command in commands)
{
  bool success = command.Execute();
  if (!success) break;
}

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.

List<ICommand> commands = new List<ICommand>;
commands.Add(command1);
commands.Add(command2);

Then the list of Command objects gets executed like this:

foreach (ICommand command in commands)
{
  bool success = command.Execute();
  if (!success) break;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文