This is an alternative way to create a new object in java. Constructors are traditionally the way to go, but since there are some advantages to using a static factory, its preferred simple vanilla constructors are.
You really need to pick Effective Java from Joshua Bloch. His first paragraph in the book. Preference to a static factory for the constructor. The benefits he mentions include:
1_ Because the static factory has names that can be descriptive.
2_ Then, a return of any subtype can be made, and not just the type of a particular class.
3_ You can handle concepts such as caching and single player games using the factory method. (you do not need to blindly create a new object).
4_ To reduce the initialization code. For example, instead of List newList = new ArrayList, we may have a method such as getStringList ();
The fourth advantage is something that I donโt really like, but I see that the Google Guava system has implemented it. Please take a book. His is one of the best books on programming for Java.
uncaught_exceptions
source share