Creating a factory method in Java that doesn’t rely on if-else

Asked By 30 points N/A Posted on -
qa-featured

 

Hello,

I need a help in factory method in Java,please

Currently I have a method that acts as a factory based on a given String.

What I want to do is avoid the entire if-else issue when the list of classes grows. I figure I need to have two methods, one that registers Strings to classes and another that returns the class based on the String of the action.

What's a nice way to do this in Java?

SHARE
Best Answer by Wade S Veith
Answered By 10 points N/A #173393

Creating a factory method in Java that doesn’t rely on if-else

qa-featured

From your question, I think that you are looking for a way to avoid modifying the factory method whenever you create a new class. 

You can try implementing your solution using Abstract Factory pattern which will eliminate the need to hard code based on strings. There are plenty of tutorials available on the internet to implement this.

Hope the info helps!

Answered By 0 points N/A #173394

Creating a factory method in Java that doesn’t rely on if-else

qa-featured

1. In Java, it can be an equivalent object. If you have used the same methods many times, then it will require a new object when it's called.

2. You can also avoid the entire issue with the help of a constructor and you can also use two of the same method.

Best Answer
Best Answer
Answered By 65 points N/A #173395

Creating a factory method in Java that doesn’t rely on if-else

qa-featured

 

Hello,

There are a lot of classes that you want to add in the future and you can also remove those which are of no use to you. This means that the code is not closed for modification. The way to reopen it is to open it for extension but close for modification. This code can be scattered everywhere in your application and it can be a nightmare.

Related Questions