Question

I have some conditions like-

List globalList = new ArrayList();
if(X.isExists)
  globalList(new XBasedClass());
if(Y.isExists && Z.isExists)
  globalList(new ZYBasedClass());
else if(Y.isExists || Z.isExists)
  globalList(new CommonBasedClass());
if(N.isExists)
....

First I thought of using State Pattern, but I realized that then for each condition I need to declare classes, and I want to limit the number classes.

Second I thought of using Decorator Pattern , but again above condition check will be required , and if that is required then does the above loop creates any issue.

My conditions just only need to add new classes into the List , nothing else and even in future if number of conditions increase, even the work will remain same ie to update the List.

So I made a private class with a static method , which just validates the condition and update the list accordingly.

Is there any better recommended design to achieve it

Was it helpful?

Solution

The creation can be delegated to a factory class. IF you have different sets for implementation types, then an abstract factory. So there is the pattern.

I am not sure if those if blocks are just an example, but they can be optimized, for example moving if(Y.isExists) to an upper block.

OTHER TIPS

I'm writing this as an answer to address several comments.

  1. I up-voted @Tech-user's answer because the factory pattern is the right thing to do in your case.
  2. There are varying levels of complexity in implementing the factory concept. "Abstract factory" is more than you need I expect.
  3. Learn more about the different categories of patterns. That will help you zero in on appropriate ones. Factory is a creational pattern. You are creating new objects. State and Decorator are not creational in nature.
  4. Others' comments advocating not using a pattern because it will complicate things misses the point of using patterns. Patterns makes code better, building your code with Object Oriented goodness. However, forcing your code into an inappropriate pattern will definitely complicate things.
  5. Dismissing patterns out of hand because "they add complexity" is really, really misguided.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top