Reputation: 1032
I have a set of different type of rules to be evaluated. Each rule has different statistics,
I'm planning to implement it based on Builder pattern, with the following code snippet
foreach(Rule rule in Rules){
var result = rule.evaluate();
var message = rule.getMessage(result);
rule.saveMassage(message);
rule.updateDB(result);
}
Here the Rule is the base type and there are sub-types for each rule type which holds properties of the rule.
Is my approach OK? or a better way of doing it?
Upvotes: 1
Views: 965
Reputation: 318
First need to clarify what the Builder pattern is. By its definition in the book Head First Design Patterns:
Use the Builder Pattern to encapsulate the construction of a product and
allow it to be constructed in steps.
From your problem description I don't know which objects are 'materials' to build up a Rule. I would suggest you using the Decorator pattern instead.
public interface Rule {
public void evaluate();
}
public class RuleType1 implements Rule {
@Override
public void evaluate() {
//Evaluation Logic of Type 1
}
}
public class RuleType2 implements Rule {
@Override
public void evaluate() {
//Evaluation Logic of Type 2
}
}
public class RuleEvaluator implements Rule {
private Rule rule;
public RuleEvaluator(Rule rule) {
this.rule = rule;
}
@Override
public void evaluate() {
// 1. Evaluation logic
this.rule.evaluate();
// 2. Update message
// 3. Update status
// 4. Update database
}
}
public class RuleDemo {
public static void main(String[] args) {
//Get the list of rules
for(Rule rule : rules) {
Rule temp = new RuleEvaluator(rule);
temp.evaluate();
}
}
}
Upvotes: 1
Reputation: 430
I think your solution is OK. But if you you want to improve design, you have two options:
1) Move this call sequence into a method inside Rule base class.
2)if you are not allowed to modify rule class interface, you need to implement Facade pattern in order to simplify Rule class usages.
Upvotes: 2