tags:

views:

88

answers:

2

I need to write a class for different "configuration objects" that hold something like "if xyz = 5 then .." to transfer some Rules and Actions to those Rules.

Can anybody please help me with a clever design of a class like that?

I'm using C#.NET 3.5

A: 

Not sure what you're after but but you could have an overridable SetDefaults() method to perform actions when creating an object and a similar ApplyRules() method to perform actions before saving an object?

Mark Redman
+2  A: 

If the rules you are referring to should map to actions, then you can have a class like this:

interface IRule<T>
{
    void Apply(T obj);
}

class PredicateRule<T> : IRule<T>
{
    public ActionRule(Func<T, bool> p, Action<T> a) 
    {
       this.predicate = p;
       this.action = a;
     }

    readonly Func<T, bool> predicate;
    readonly Action<T> action;

    public void Apply(T obj)
    {
      if (this.predicate(obj))
          this.action(obj);
    }   
}

So then your "if xyz = 5 then .." rule could be declared like this:

var r = new PredicateRule<XyzClass>(x => x == 5, x => { //then...  });
eulerfx
+1 -- that's close to where I was going with this one until your answer popped up. I was thinking of storing them in a Dictionary<IRule<T>,Action<T>> that would allow you to scan through a set of rules and apply any actions where the rule evaluated to true.
tvanfosson
Hehe...IRule! You drool!
Bryan Watts
I think an assignment from rules to actions in a dictionary is a good idea. Would you declare a Rule and an Action Class and then assign them in the Dict?
Kai