Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should the getInstance() method in Factory pattern be static?

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);
like image 693
rkg Avatar asked Sep 12 '11 20:09

rkg


2 Answers

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...

like image 170
DaveFar Avatar answered Oct 09 '22 00:10

DaveFar


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.

like image 36
cobaltduck Avatar answered Oct 08 '22 23:10

cobaltduck