Passing parameters of various types to a function defined on an interface in C #

I want to apply a set of rules to a set of business objects. These are simple rules, and I would not want to use any existing business rule mechanism.

I need to pass a different context to each of the rules, so theoretically, each rule may require different parameters. This is how I do it now. Is there any other / better way?

Note. I appreciated the use of the visitor pattern, but there seems to be too much effort for this particular scenario. Actual rules are not much more complicated than what I have in my example.

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); } 

Update: I forgot to add to my sample my need for downcasting.

+4
source share
1 answer

Your code is indeed a visitor template. It would be clearer if the business object had a method such as BusinessObject.Apply (BusinessRule rule) {rule.apply (this); };

It performs the same task as a full-scale implementation: you can add operations (business rules) without expanding the object on which operations are performed (business object).

You may be interested in using Composite so that you can apply a set of rules as a single rule. You may also be interested in being a little more outspoken about what callas you use in your implementation for visitors, but if this works for you, go for it.

+2
source

Source: https://habr.com/ru/post/1441576/


All Articles