Search code examples
javadesign-patternsfactory-pattern

Factory pattern in java


I was working with java code that is supposedly using the Factory pattern, but I'm not completely convinced by the pattern.

My code does this:

// the factory
class SomeFactoryImpl {
   Set<SomeClass> getSomeListOfObjects();
}

And somewhere in the code:

{ ...
    SomeFactory factory = new SomeFactoryImpl();
    Set<SomeClass> list = factory.getSomeListOfObjects();
}

The point I'm pondering is, if factory classes don't have a static create() method, then one will need to instantiate a factory, which IMO should be just as complex as instantiating an object itself.

I don't consider the argument that such a factory can return collections of objects to be produced is good enough. I feel there can be cleaner workarounds, if a factory instance needs to be created before actually creating objects from the factory.

I feel that it is better if the create method a static method of the factory class. But I'm also sure that my opinion is not completely "correct".

So can the SO community give examples where instantiating a Factory object is better than using static create methods?

Also, I came across an answer to a similar question, which listed these links and the answer: so I need to know clearly the difference between FactoryMethodPattern, FactoryMethod and CreationMethod with code examples.


Solution

  • Using an instance of a factory shows the real benefits when combined with dependency injection.

    So in your example, instead of:

    { ...
        SomeFactory factory = new SomeFactoryImpl();
        Set<SomeClass> list = factory.getSomeListOfObjects();
    }
    

    You would have:

    public ThisClass(SomeFactory someFactory) {
        this.factory = someFactory;
    }   
    

    then later...

    { ...
        Set<SomeClass> list = factory.getSomeListOfObjects();
    }
    

    Some points:

    • In this circumstance your class does not have any reference to a concrete factory, and doesn't need to know about SomeFactoryImpl, it only knows about the abstracted SomeFactory.
    • In this case the factory instance that's being passed around can be configured on an instance basis, rather than a static basis, which tends to be (in my opinion) a nicer way to deal with it. If you can make the factory instance immutable then you can really cut down the multi-threading worries.
    • Having a static call to give you an instance isn't really much better, the reference to the class that creates it is still a concrete implementation detail, it's just higher up - though that may make it high enough to solve your problem.

    I know this only addresses a subset of your question...