In most of the factory pattern implementations, the getInstance
method is usually declared as static. The main advantage of factory pattern is to hide the implementation details, but why does getInstance()
method needs to be static? Is instantiating a new Factory Object a bad practice?
XYZFactory factory = new XYZFactory();
XYZObj obj = factory.getInstance(TYPE);
Vs
XYZObj obj = XYZFactory.getInstance(TYPE);
A lot of factory methods are used to offer an instance of the class itself, without the class exporting any constructors (see e.g. Josh Bloch item 1). If the factory method were an instance method, you wouldn't have an object of the class to start with.
Furthermore, getInstance()
is usually independent of any existing instance, so it should be declared static. If it depends on one, a prototype (i.e. clone()
) is often preferred.
Finally, you should distinguish between factory method public static getInstance()
and an abstract factory, which is a class that hides implementation details often for several interfaces. You must, of course, be able to instantiate subclasses of the abstract factory. You can find a great introduction to creational patterns (Abstract Factory, Factory Method, Prototype, amongst others) in the classic Design Patterns book from the Gang of Four. It also gives an example of a non-static factory method intermixed with a prototype. So you see, many variants are possible...