Search code examples
javafactory-pattern

how to determine the subclass type in a factory pattern other than using if else and switch?


I wanted to try the factory pattern and was able to implement it, but when
generating for more than a few classes, i thought this will be ugly!! so any clarity or suggestions would be really appreciated...

My Superclass:

public abstract class Output {

    public abstract void generate(Data dat); }

i got my other classes extending from Output like

public class generateXML extends Output{
.
.
.
}

My question is related to here:

public class generatorFactory(){

public Output generate(String str){   

// or getting an Object as an argument like (Object obj)

if(str.equals("xml"){  
return new generateXML();  
}  
else if.........  
......  
}

Is there any way we can determine the subclass type avoiding checking for each type??


Solution

  • You can use newInstance() to instanciate a generator whose classname you've built from the parameter:

    public Generator getGenerator (final String type)
    {
        final Class generatorClass = ClassLoader.getSystemClassLoader().loadClass("Generator"+type);
        final Generator generator = (Generator) (generatorClass.newInstance());
         return generator;
    }
    

    PS: I highly rate you to follow the rules of Java: if generateXML is a class, it should be written GenerateXML.

    More over: take care by naming your classes. (1) An Object generateXML shouln'd extend Output, because it isnt' an output. (2) "GenerateXML" is a verb, i.e. an action. It is therefore not a correct word to name an object, but a method. You could name the object per example "XMLGenerator".