Background:
I have a JSON object (named JSONConditionObject) which looks like the following,
{ "condition1":"value1", "condition2":"value2,value3 ..." //more fields below very likely to be added/changed //also the nature of values for a condition (String/List) might change as well //For eg, it can be another json itself } I want to read this JSON object -> validate the conditions and if all conditions are true, perform some task.
My Approach:
The best I could think of is the Decorator pattern to make the code extensible/flexible. Each field will be a decorator around a base object (base object will have logic to perform the final task if all conditions are true),
public abstract class ConditionDecorator extends Condition{ private Condition condition; // Condition is the top level abstract class signifying a json condition @Override public void apply(Task task) { if(this.shouldApply(task)){ condition.apply(task); } } } Then each condition in the JSONConditionObject will have its own class like so,
public class Condition1Context extends ConditionDecorator { private Condition condition; private String condition1; public Condition1Context(Condition condition, JSONConditionObject jsonConditionObject){ super(condition); this.condition = condition; this.condition1 = jsonConditionObject.getCondition1(); } @Override protected boolean shouldApply(Task task) { //will have logic for validating condition ... } } Finally, I read the JSONConditionObject and return a variable of type Condition which can be used to validate the conditions one after another. If a new condition is added in the future, I will just have to create a new class for it (like Condition1Context above) and decorate the final Condition object with it.
My Question:
This approach is a bit verbose and leads to generation of a lot of classes in my project (one single class for each condition). Would there be another way which is a bit more elegant and would require lesser code?