Search code examples
javafactory-pattern

Value of Factory Classes


I can appreciate the value of factory methods, but I'm struggling with the value of using dedicated factory classes.

This will work:

class Brady
{
    int age;
    String name;
    static Brady create(String who)
    {
        if(who.equals("Cindy"))  return new Cindy();
        if(who.equals("Jan"))    return new Jan();
        if(who.equals("Marcia")) return new Marcia();
        return null;
    }
}
class Marcia extends Brady {}
class Cindy extends Brady {}
class Jan extends Brady {}

...
Jan jan = (Jan)Brady.create("Jan");

So is there any good reason to use a factory class instead?

class Brady
{
    int age;
    String name;
}
class Marcia extends Brady {}
class Cindy extends Brady {}
class Jan extends Brady {}

class BradyFactory 
{
    static Brady create(String who)
    {
        if(who.equals("Cindy"))     return new Cindy();
        if(who.equals("Jan"))       return new Jan();
        if(who.equals("Marcia"))    return new Marcia();
        return null;
    }
}

Jan jan = (Jan)BradyFactory.create("Jan");

It just seems like a waste of additional code. I do understand the usefulness of a factory class when an instance is needed:

class BradyFactory 
{
    Brady brady;
    BradyFactory(String who)
    {
        if(who.equals("Cindy"))
            brady = new Cindy();
        else if(who.equals("Jan"))
            brady = new Jan();
        else if(who.equals("Marcia"))
            brady = new Marcia();
    }
    public BradyFactory addChore(Chore chore) 
    { 
        brady.addChore(chore);
        return this;
    }
    Brady create()
    {
        return brady;
    }
}

Jan jan = (Jan)new BradyFactory("Jan")
            .addChore(Chore.Dishes)
            .addChore(Chore.Washing)
            .create();

...or when a subclass of the Factory is needed.

So my question is: is there any value to putting simple factory methods in a dedicated factory class other than when an instance of the factory, or a factory subclass, is needed?


Solution

  • Generally, a factory method is placed in a separate class when you're going to be plugging in different implementations of the object at different times. The factory is a well-known entry point to obtain an instance of the object, and needs to always be findable. But the factory may be selecting among multiple implementations, or dynamically loading them via reflection, with the caller not knowing (or caring) which implementation is returned.