开发者

Implementing a rules system

I'm building an app for android which allows objects to be merged together based on certain conditions. At the moment I'm looking to do this using if statements (nested or not) and am just wondering if there is a better way to do this so it is more flexible and easily expanded.

For example, I have 6 objects, 3 of them are red, 2 are blue and 1 is green.

The rules that can be applied to that are:

  • 3 red can be merged
  • 开发者_如何学运维
  • 2 blue can be merged
  • 1 red and 1 blue and 1 green can be merged
  • 1 red and 1 blue can be merged
  • 1 red and 1 green can be merged
  • 1 green and 1 blue can be merged

That is a very basic example of it. There will be a lot more than that.


I would probably do something in region of:

Create a Rule-class, that holds the logic for a given rule (your if-statements). A Rule should have a priority, so that it can be matched up against other rules to determine what rule should be considered first. It also needs a method to which an undetermined number of objects can be passed to, which checks if these objects fulfill the rule.

Create a RuleEngine, which holds a sorted list (by priority, highest first) of all rules. You then pass the objects you want to match towards the rules to the engine and the engine runs through them, breaking the loop if a rule is fulfilled:

for( Rule rule : rules ) {
  if( rule.check( objects ) ) {
    //Do what needs to be done
    break;
  }
}

I don't know if this makes sense to you - I hope it does.

Also if we're talking thousands of rules this solution is not optimal. In that case you would want to determine which rules the object might have a chance to fulfill before checking them (e.g. if you have two red and one green, there's no need to check the 'one-of-each'-rule).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜