我正在尝试想出(我希望的)一个稍微简单的工作流引擎。
基本上,我有一个具有 Status 属性的类对象。为了使其进入不同的状态,它应该经过验证步骤。如果没有验证错误,状态将会更改。
不过,在验证过程中,我希望允许验证器组件向用户请求信息或发出警报消息。
我的问题是,到目前为止,该应用程序是作为 Windows 窗体应用程序构建的,但我们知道有必要拥有它的 Web 版本。因此,两者的验证都是相同的,但应该允许每个人都有自己的方式来请求信息或提醒用户。我想象的方法是在我的验证类上使用委托(delegate)和事件。
这是我得到的:
//This is the class which will have its status changed
public class MyClass
{
public int Status { get; set; }
}
//This class represent a transition from one status to another
public class Transition
{
public int FromStatus { get; set; }
public int ToStatus { get; set; }
}
//Common interface for all validators
public interface IWorkflowValidator
{
bool Validate(MyClass object);
}
//This is the base workflow class with the main logic
public abstract class BaseWorkflow
{
//This holds all the possible transitions with the validator type responsible for its validation.
//For example:
// var transition = new Transition(1, 2); //From 1 to 2
// validatorsMap.Add(transition, typeof(ValidatorFrom1To2)); //ValidatorFrom1To2 class would be used to validate transition from status 1 to 2.
protected Dictionary<Transition, Type> validatorsMap = null;
//Main logic for a transition
public void PerformTransition(MyClass object, int ToStatus)
{
int currentStatus = object.Status;
var requestedTransition = new Transition(currentStatus, ToStatus);
//Get the validator specified for this transition
var validatorType = validatorsMap[requestedTransition];
//Instantiate a new validator of that type
var validator = (IWorkflowValidator)Activator.CreateInstance(validatorType);
//Gets the result of the validator
bool results = validator.Validate(object);
//If validation succeded, it will perform the transition and complete the execution
}
}
我的主要问题涉及验证器本身。正如我所说,我需要验证器能够请求特定转换所需的信息。所以,这就是我拥有第一个验证器的方式:
public class AlertHandlerArguments {}
public delegate void AlertHandler(AlertHandlerArguments args);
public class MyFirstValidator : IWorkflowValidator
{
//Event used to send an alert to the user
public event AlertHandler OnAlert;
//Implementation of IWorkflowValidator
public bool Validate(MyClass object)
{
SendAlert();
}
void SendAlert()
{
if (OnAlert != null)
OnAlert(new AlertHandlerArguments());
}
}
我在这里的想法是创建一个包含所有类型事件的接口(interface),并在所有验证器上实现这些接口(interface)。然后我的抽象 BaseWorkflow 类可以为这些事件附加处理程序。
但是,我的抽象类无法实现这些事件的最终代码。这些是供接口(interface)使用的,到目前为止我的抽象类是独立于平台的(桌面、网络)。这实际上就是我将此类创建为抽象类的原因。
这样,我就可以让我的 Windows 窗体项目拥有具体类型的 BaseWorkflow 并附加事件来显示 Form 对象以请求信息。
另一种选择是在基类上附加处理程序并在 UI 级别覆盖具体类。
我的方向正确吗?如何允许验证器向用户请求信息(在 UI 级别),并在业务层保留一些逻辑,以便它适合 Windows 表单和 Web?
感谢您对此事提出的任何意见。提前致谢。
Ps.:直到我写完之后,我才意识到我不太确定如何在网络应用程序上使用它。我的意思是,Windows 窗体应用程序可以中断执行并为用户显示输入表单,但这在 Web 上不起作用。这是否意味着我的工作流程结构仅适用于桌面应用程序?
最佳答案
首先,如果您想在工作流程中使用各种验证器,并且验证器将依赖于环境=>,因此您可能需要策略模式。但你需要小心这一点。
创建包含所有类型事件的接口(interface)可能不是一个完美的想法,因为要做的事情太多了。更好的是,验证器应该具有一些公共(public)状态,并且该状态可以取决于验证结果,然后工作流应该只检查验证器状态。我只是认为使用委托(delegate)作为函数参数而不是使用事件会更好。
关于c# - 我如何建模和构建这个工作流引擎?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14378880/