I have Foo.java, which is interface.
And lots of classes that implement it. Bar1.java , Bar2.java etc.
I have a method in frontend, that is like this: getBar(String bar)
I could just do it like this:
if(bar.equals("Bar1")) {
return new Bar1();
}
But can I somehow do it, that everytimes something new implements Foo.java , then I don’t have to update my method, with new ELSE statement.
I thought like each implementation have unique ID or something, which I add to BarX.java , whenever I create it.
Any suggestions or thoughts? I thought maybe I can use enum or smthing or any other solution.
FYI: You realize, of course, that you should not write this:
You should do it this way:
Looks like you need a factory (aka virtual constructor). If all your Foo implementers have a default constructor, you can do this:
There are exceptions to be handled; I don’t have time to spell them out for you. You should see the idea. All you need to do is write a new class and your factory can handle it.
If there are other constructors, just elaborate the theme with parameters and additional calls. This should get you started.