哪种设计模式可以做到这一点?
我有一个类似于工作流程的流程,假设如下:
- 准备
- 吃饭
- 把你的东西扔进垃圾箱
- 清理桌子
现在我想做的是即使用户取消了“吃”事件我希望他们“清理桌子”同样适用于“准备”和“拿走你的东西”到垃圾箱”阶段。
目前在我的实现中,我必须进行多次检查,有时我最终会调用“清理表”两次,以及当我添加更多步骤时出现一些其他分支问题。
是否有明确定义的设计模式来处理这种流程? (AFAIR 有一个我只是不记得它的名字了。)
I've got a process something like a workflow, assume it like this:
- Prepare
- Eat
- Take your stuff to bin
- Clean up the table
Now what I want to do is even the user cancels the "Eat" event I want them to "Clean up the table" same goes for "Prepare" and "Take your stuff to bin" stages.
Currently in my implementation I had to do several checks and sometimes I end up like calling "Clean up table" twice, and some other branching issues when I add couple of more steps.
Is there any well defined design pattern to deal with this kind of flows? (AFAIR there was one I just can't recall the name of it.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这是通过状态模式解决的。 如果你测试驱动逻辑,它会很顺利。
This is solved with the State pattern. If you test drive the logic it'll go smoothly.
听起来像模板方法模式。
或者您可以通过组合和策略模式来做到这一点。
如果您开始有复杂的逻辑,那么 状态模式 可能会更好。
Sounds like Template method pattern.
Or you can do this via composition and Strategy pattern.
If you start to have complicated logic, then State pattern could be better.
如果您使用 C++:资源获取即初始化。
在没有某种确定性终结的语言(C#、Java 等)中,这个问题通常还没有得到很好的解决。
If you're working in C++: Resource Acquisition is Initialization.
This problem generally hasn't been solved well in languages without some sort of deterministic finalisation (C#, Java etc.)
我的朋友的状态模式将使这项工作最终成功。
State Pattern my firend is what will make this work at end.
在 C#/.NET 中,我们有
IDisposable
模式。 我确信您可以用另一种语言实现类似的东西,无论它是否有垃圾收集器(尽管实现会略有不同)。关于工作流程方面,我将遵循 WCF 中 Web 服务的设计模式(即
Begin
和Cancel
方法)。 如果您不认为它对于您的情况来说太过分了,Windows Workflow Foundation 可能是最好的方法。In C#/.NET, we have the
IDisposable
pattern. I'm sure you could implement something similar in another language, whether or not it has a garbage collector (though the implementation would differ slightly).Regarding the workflow aspect of this, I would just follow the design pattern of web services in WCF (i.e.
Begin
andCancel
methods). If you don't consider it overkill for your circumstances, the Windows Workflow Foundation may be the best way to go.