When and how should we use a constructor
Foo bar = new Foo();
And when and how should we use getInstance() (static factory methods)
Foo bar = Foo.getInstance();
What is the difference between these two? I have always used a constructor, but when should I use getInstance()
instead?
A static factory method is a public static method on the object that returns a new instance of the object. These type of methods share the same benefits as the traditional factory method design pattern. This is especially useful for value objects that don't have a separate interface and implementation class.
getInstance(String algorithm) The getInstance() method of java. security. Provider class is used to return a Signature object that implements the specified signature algorithm. This method traverses the list of registered security Providers, starting with the most preferred Provider.
A factory constructor is a constructor that can be used when you don't necessarily want a constructor to create a new instance of your class. This might be useful if you hold instances of your class in memory and don't want to create a new one each time (or if the operation of creating an instance is costly).
The factory method is a smart way to create objects in Java and provides several advantages over the traditional approach of creating objects using constructors in Java. It can also improve the quality of code by making the code more readable, less coupled, and improves performance by caching.
Everybody seems to focus on singletons while I think that the question is actually about constructor vs static factory methods.
This is actually Item 1: Consider static factory methods instead of constructors of Effective Java by Joshua Bloch:
Item 1: Consider static factory methods instead of constructors
The normal way for a class to allow a client to obtain an instance of itself is to provide a public constructor. There is another technique that should be a part of every programmer’s toolkit. A class can provide a public static factory method, which is simply a static method that returns an instance of the class. Here’s a simple example from
Boolean
(the boxed primitive class for the primitive typeboolean
). This method translates a boolean primitive value into aBoolean
object reference:public static Boolean valueOf(boolean b) { return b ? Boolean.TRUE : Boolean.FALSE; }
Note that a static factory method is not the same as the Factory Method pattern from Design Patterns [Gamma95, p. 107]. The static factory method described in this item has no direct equivalent in Design Patterns.
A class can provide its clients with static factory methods instead of, or in addition to, constructors. Providing a static factory method instead of a public constructor has both advantages and disadvantages.
Advantages (quoting the book):
Disadvantages (still quoting the book):
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