design-patterns - 将多个顺序功能作为一个工作单元执行并支持回滚的设计模式
问题描述
我有一个复杂的审查申请提交流程,需要执行几个步骤。
ReviewService.CreateReview()
- CheckReservedTimeslotIsAvailable
- 流程支付
- 创建会议
- 插入评论
- 更新财经杂志
- 完成文件
- 通知
所有这些步骤都在 CreateReview() 方法中编码,并且变得不可读、难以管理。此外,当前的实现不支持回滚。
所以这个想法是创建一个 Orchestrator 类并构建步骤序列。如果完成所有步骤,编排器将确保创建成功的审核。如果任何步骤未能完成,则所有已完成的前面功能都将回滚以确保数据完整性。这与 Saga 模式(Orchestrated)几乎相同,但稍有变化,步骤不是微服务。
这是使用正确的模式吗?还是命令模式是一个不错的选择?请指教。
BaseOrchestrator ... 使用系统;使用 System.Collections.Generic;
/// <summary>
/// Facilitates runnning of the pipeline operations.
/// </summary>
/// <typeparam name="T">The type of object orchestrator is executed on.</typeparam>
public abstract class BaseOrchestrator<T> : IOrchestrator<T>
{
protected T data;
protected List<Action> Steps;
protected int rejectReason;
public BaseOrchestrator<T> Begin(Action stepToExecute)
{
RegisterStepToExecute(stepToExecute);
return this;
}
public BaseOrchestrator<T> Step(Action stepToExecute)
{
RegisterStepToExecute(stepToExecute);
return this;
}
public BaseOrchestrator<T> End(Action stepToExecute)
{
RegisterStepToExecute(stepToExecute);
return this;
}
public BaseOrchestrator<T> WithRollback(Action stepToExecute)
{
RegisterStepToExecute(stepToExecute);
return this;
}
protected BaseOrchestrator<T> RegisterStepToExecute(Action stepToExecute)
{
Steps.Add(stepToExecute);
return this;
}
public BaseOrchestrator<T> StepBuilder()
{
Steps = new List<Action>();
return this;
}
/// <inheritdoc/>
public void Execute(T data)
{
...
}
}
...
解决方案
在这种情况下,命令模式更好,因为您正在构建查询。您不必处理多个数据库中的数据,因此不必处理 2PC。然而,如果您使用 Saga,您将在每种方法上提交事务,这对您并没有太大的好处,并且从长远来看可能会增加更多的复杂性。
假设出现暂时的网络问题并且一种方法失败并且回滚在前两次回滚时有效,但在下一次回滚时失败?
推荐阅读
- pytorch - 为什么 Pytorch 的 mul() 函数与 numpy 结合使用时会出现 TypeError?
- c++ - 具有运行时多态性的 C++ 双重分派?
- r - 根据子组和 2 列计算值的数量
- android - Kotlin/Android 中的“赋值不是表达式”错误
- ios - 从添加到 keyWindow 的视图中使用 hitTest() 或 point(inside, with event) 转发事件
- java - 配置为侦听端口的 Tomcat 连接器无法启动?
- javascript - bind() 方法如何与“this”关键字相关联?
- javascript - Square POS API 添加唯一 ID,可以吗?
- nlog - NLog:什么是布局和布局渲染器?
- unikernel - 如何在 Windows 上使用 OSv unikernel 构建我的 Java 应用程序