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...
Daves answer is absolutely correct if the factory method is in the class itself. For a factory method in some other class, I think it is a matter of style. I would go back to the basic question of when is something static: does this method provide behavior to the class as a whole, or to specific instances of the class? I argue factory methods typically offer class-level behavior.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With