我想将一组规则应用于业务对象的集合。这些是简单的规则,我不想使用任何现有的业务规则引擎。
我需要将不同的上下文传递给每个规则,因此理论上每个规则可能需要不同的参数。以下是我目前的做法。还有其他/更好的方法吗?
注意:我已经使用访问者模式进行了评估,但对于这种特定场景来说似乎付出了太多努力。实际规则并不比我在示例中的复杂得多。
interface IParamBase {}
interface IParam : IParamBase
{
string MyProperty {get; set;}
}
class Param : IParam
{
public string MyProperty {get; set;}
}
interface IRule
{
void Setup(IParamBase param);
void Apply(BusinessObject businessObject);
}
class Rule :IRule
{
IParam _param;
public void Apply(BusinessObject businessObject)
{
businessObject.AssignedFromRule = _param.MyProperty;
Console.WriteLine(businessObject.AssignedFromRule);
}
public void Setup(IParamBase param)
{
_param = param as IParam;
}
}
class BusinessObject
{
public string AssignedFromRule {get; set;}
}
void Main()
{
var rule = new Rule();
var param = new Param();
param.MyProperty = "my property";
BusinessObject businessObject = new BusinessObject();
rule.Setup(param);
rule.Apply(businessObject);
}
更新:我忘了在样本中添加我需要向下转换的内容。