I have already posted this question, I added more code for clarifications:
I have recently implemented the chain of responsibility design pattern in Java (To process many business requirement rules). Each class handle one business rule and call the next rule if it cannot be handled by that class.
I want to be able to call many other rules (I want to chain them by using another class that includes other rules (which has the implementation of the same design pattern) as another chain to process other rules.
The first chain will call the second chain of rules. Is there a way to add a property on the first chain to include the next processor(chain of rules) to call?
Should I add another property to handle nextProcessor?
Thank you, I hope to get some help or directions...
This is what I have done so far :
public abstract class AbstractPriorityRule implements IPriorityRule {
protected IPriorityRule nextRule;
protected IRuleProcessor nextProcessor;
@Autowired
protected Context ctx;
public void setNextRule(IPriorityRule nextRule) {
this.nextRule= nextRule;
}
protected OutputDto applyNextRuleIfExist(Input input) {
if (this.nextRule != null) {
return this.nextRule.apply(inputForManyProxiesRules, ctx);
}
OutputDto outputDto = ctx.getOutputDto();
return outputDto;
}
}
This chain of rules will be calling PriorityRule:
public abstract class AbstractMultiplePrxRule implements IMultiplePrxRule {
protected IMultiplePrxRule nextRule;
protected IRuleProcessor nextProcessor;
@Autowired
protected MultiplePrxContext ctx;
public void setNextRule(IMultiplePrxRule nextRule) {
this.nextRule= nextRule;
}
protected OutputDto applyNextRuleIfExist(Input inputForManyProxiesRules) {
if (this.nextRule != null) {
return this.nextRule.apply(input, ctx);
}
else if(this.nextProcessor != null){
return this.nextProcessor.apply(input, ctx);
}
OutputDto outputDto = ctx.getOutputDto();
this.ctx = null;
return outputDto;
}
}
And this the chain that will be defining the rules for MultiplePrx:
@NoArgsConstructor
public class MultiplePrxChainFactory {
private static MultiplePrxsChainFactory instance = new MultiplePrxChainFactory();
public static MultiplePrxChainFactory getInstance(){
return instance;
}
public IMultiplePrxRule createChainOfRules(Optional<IRuleProcessor> nextRuleProcessor, IMultiplePrxRule... rules){
List<IMultiplePrxRule> prxRules = Arrays.asList(rules);
IMultiplePrxRule previousRule = prxRules.stream().findFirst().get();
for (int i = 1; i < prxRules.size(); i++) {
IMultiplePrxRule currentRule = prxRules.get(i);
previousRule.setNextRule(currentRule);
previousRule = currentRule;
}
if(nextRuleProcessor.isPresent()){
// this will set the next chain of rules to call (it will be IPriorityRule)
prxRules.get(proxRules.size()-1).setNextProcessor(nextRuleProcessor.get());
}
return prxRules.stream().findFirst().get();
}
}
Aucun commentaire:
Enregistrer un commentaire