Static factory methods, an alternative to public constructors
The most widely used technique to allow other parts of our Java programs, to get objects of a certain type, is to create public constructors.
There is also another technique which is that provides various advantages and it would be highly recommendable for every programmer to know. Classes can provide static factory methods. This methods are another way of returning instances.
More descriptive naming is possible
Methods have names, so we can be more descriptive when constructing our objects. Constructors cannot have names, but methods can, so by having this types of methods we can express more fluently how the object is constructed. So instead of this:
We can create our objects like this:
Resources optimisation
Every time the keyword new is called, a new instance is created. In many occasions, specially in large systems, programmers need to be careful with resources. It is not rare to see static factory methods used in some design patterns. The Singleton and fluent Builder patterns will use static factory methods:
- having cached objects and manage that they are cleaned properly.(Google for Singleton pattern).
- work with immutable objects which provide predefined state.(Google for Builder Pattern)
Flexibility if required.
In our example we restricted inheritance by making Product.java final, but if we wanted to we could have a more flexible factory by using use sub-classes. This is a very interesting feature that could bring a bit of extra flexibility to your static factory if you wanted. In the following piece of code you will see a very trivial implementation of a cached object:
In this example you can see how the static factory method can be used to create instances of different types or implementing types:
Originally posted at: http://javing.blogspot.com/2012/10/static-factory-methods-have-many.html