Having worked with C# before, I have considered
Calendar cal = Calendar.getInstance();
to be a singleton method according the GoF Singleton pattern (Wikipedia) and I wondered how to create two calendars, since Date
is somewhat deprecated.
From the documentation
Gets a calendar using the default time zone and locale.
and the overloads
getInstance(TimeZone zone)
getInstance(Locale aLocale)
this seemed to me to be a generalization of the singleton pattern to create a singleton per time zone and locale. But I wanted two calendars in the same time zone.
However, when I conducted the test
@Test
public void test()
{
Calendar cal = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
assertTrue(cal == cal2);
}
it failed, telling me that this getInstance()
method is actually not a singleton pattern getInstance()
method but something else.
So, does getInstance()
in general denote a singleton according the singleton pattern in Java or not? If so, what are the key wordings in the Java documentation to find out it is or is not a singleton? If not, how do I identify a singleton pattern in Java? Or is Calendar
the only exception?
I'd not like to implement a unit test each time I meet a getInstance()
call.
I have read this answer to "What is an efficient way to implement a singleton pattern in Java?", which would work exactly like in C#, which contradicts the Calendar
implementation.