首页 > 解决方案 > 将多个顺序功能作为一个工作单元执行并支持回滚的设计模式

问题描述

我有一个复杂的审查申请提交流程,需要执行几个步骤。

ReviewService.CreateReview()

所有这些步骤都在 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)
    {
        ...
    }
}

...

标签: design-patternsrollbacksequential-workflow

解决方案


在这种情况下,命令模式更好,因为您正在构建查询。您不必处理多个数据库中的数据,因此不必处理 2PC。然而,如果您使用 Saga,您将在每种方法上提交事务,这对您并没有太大的好处,并且从长远来看可能会增加更多的复杂性。

假设出现暂时的网络问题并且一种方法失败并且回滚在前两次回滚时有效,但在下一次回滚时失败?


推荐阅读