But, in case I get a similar question on the exam, I am seriously considering to choose "getInstance" instead of "newXXX".
Your examples for "newXXX" factory methods are perfectly valid. I also noticed a lot of other "newXXX" in several other places:
- java.nio package:
+ FileSystems.getDefault().newWatchService();
+ several methods in Files class
+ several methods in Channels class
+ some other methods located in various classes in this package
- java.util.concurrent package (your examples + some other methods that create threads, tasks, lock conditions etc.)
- other places
I also agree that we are used to have "getInstance" method in a Singleton class. But, in case the "getInstance" method receives arguments, I believe it acts as a Factory. I want to illustrate this with your "Singleton example" : Currency.getInstance(Locale). If you look over the implementation, I believe you agree that it is a Factory; it does not provide a Singleton reference.
Maybe the best example is Calendar.getInstance(Locale). In the implementation there are various Calendar types (GregorianCalendar, BuddhistCalendar, JapaneseImperialCalendar), but it is hidden to the client the actual class that is being instantiated.
And there are plenty of other classes with "getInstance" methods that have arguments.
In fact neither Calendar.getInstance() is not returning a Singleton. This can be very easily spotted from the implementation or from the following code (the result is 2 different numbers so there are 2 different instances):
Code: Select all
Calendar instance1 = Calendar.getInstance();
Thread.sleep(100);
Calendar instance2 = Calendar.getInstance();
System.out.println(instance1.hashCode());
System.out.println(instance2.hashCode());