I’m attempting to implement a ‘Requirements’ type system into a program. It seemed pretty simple in my head, but actually making it abstract enough to be useful is proving more difficult than anticipated.
Here is what I am trying to do …
enum Condition {
Not, Exists, Exceeds
}
abstract class Requirement {
// base class
Condition Condition { get; set; }
}
class ScoreRequirement : Requirement {
// a specific 'score' is required
}
class TraitRequirement : Requirement {
// a specific 'trait' is required
}
class SatisfyingObject {
// this is the class that has to satisfy the requirements
IDictionary<Trait, int> Traits { get; set; }
}
If I know the exact thing that has to be satisfied in code-time, this is very simple. But the goal is to let people add requirements later. There will be other types that derive from Requirement, as well.
So a requirement might work like this …
var obj = new Item {
Requirements = new List<Requirement> {
new ScoreRequirement { Trait = "One", Score = 2, Condition = Condition.Exceeds }
}
}
So the concept seems pretty simple. You would call upon an object..
var satisfying = // get the satisfying object;
if( satisfying.Satisfies( obj.Requirements ) )
return true;
The problem I am running into is really how to code the Satisfies method – in specific I am not sure how to relate it to the Condition parameter. I’d like people to be able to set up some fairly generic ‘requirements’, but the logic behind this is very confusing to me. Since the requirements are not known at design time, I cannot really hard code any of them.
Any suggestions?
If this isn’t a learning project than I would highly recommend you look at using something that is already built for this:
If however you are doing this as a simple learning project, than you have 2 basic approaches you could take:
Of the two, delegate based is going to be much simpler to implement, but less flexible. I have implemented this pattern several times and the concept is simple. Here is about the most basic concept you can get.
You can use it in code like this:
Now, this was all from memory, so there
may be someare probably coding/compiler errors in all this, but hopefully you get the general idea.Again, if this isn’t a learning project, then don’t reinvent the wheel unless you are planning to learn more about wheels 🙂