Java – Instantiating a Class Implementing an Interface

java

I have an interface called Cell. In the start of the code, I read input data from which I can come to know the implementing class (not as a class object but I can know for example the string). And after that I need to call the constructor for the implementing class to initialize an object.

What would be the best way to implement that. The first thing in my mind is to do something like this (Cell is an interface, Sphere and Rectangle implements Cell. I can set a boolean flag called sphere after reading the input data):

Cell startcell;
if (sphere)
    startcell = new Sphere(0);
else
    startcell = new Rectangle(0);

But is this good design?

Best Answer

Looks like Factory pattern, which is quite "endorsed" by design gurus, so to speak. See bottom of that Wikipedia pages for existing creation patterns for OOP languages, like Java.

Related Topic