Why should the getInstance() method in Factory pattern be static?
In most of the factory pattern implementat开发者_如何学运维ions, 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.
Factory should give you instances of products, not instances of itself. It's rather like Singleton.
Because you use a factory to create objects. What you need is object instances not factory instances. So you usually look for the simplest, cleanest way of doing it.
It isn't useful to have more instances of the factory laying around. The factory instances will be useless after creating the object(s), so why create useless factory objects when just one long lived instance will do?
精彩评论