Java private constructor and getInstance() method. Why?

Status
You're currently viewing only Solomonoff's Secret's posts. Click here to go back to viewing the entire thread.
Not open for further replies.
[url=http:/civis/viewtopic.php?p=25785581#p25785581:3uc4v4vz said:
Pont[/url]":3uc4v4vz]If you "new Calendar()", you're getting a Calendar and nothing but a Calendar.

If you call "Calendar.getInstance()", you could be getting an instance of an object that is a Calendar or a descendant of Calendar. It could be a CalendarPrivateVendorImplementationFixedForBothY2Kand2038bug.
In the case of Calendar, this is the real reason (obviously Calendar shouldn't be a singleton because it's mutable). From the Calendar source, it's obvious that there's logic to instantiate an implementation of Calendar appropriate for the current locale:
Code:
    /**
     * Gets a calendar using the default time zone and specified locale.
     * The <code>Calendar</code> returned is based on the current time
     * in the default time zone with the given locale.
     *
     * @param aLocale the locale for the week data
     * @return a Calendar.
     */
    public static Calendar getInstance(Locale aLocale)
    {
        Calendar cal = createCalendar(TimeZone.getDefaultRef(), aLocale);
        cal.sharedZone = true;
        return cal;
    }

    private static Calendar createCalendar(TimeZone zone,
                                           Locale aLocale)
    {
        Calendar cal = null;

        String caltype = aLocale.getUnicodeLocaleType("ca");
        if (caltype == null) {
            // Calendar type is not specified.
            // If the specified locale is a Thai locale,
            // returns a BuddhistCalendar instance.
            if ("th".equals(aLocale.getLanguage())
                    && ("TH".equals(aLocale.getCountry()))) {
                cal = new BuddhistCalendar(zone, aLocale);
            } else {
                cal = new GregorianCalendar(zone, aLocale);
            }
        } else if (caltype.equals("japanese")) {
            cal = new JapaneseImperialCalendar(zone, aLocale);
        } else if (caltype.equals("buddhist")) {
            cal = new BuddhistCalendar(zone, aLocale);
        } else {
            // Unsupported calendar type.
            // Use Gregorian calendar as a fallback.
            cal = new GregorianCalendar(zone, aLocale);
        }

        return cal;
    }
 
Status
You're currently viewing only Solomonoff's Secret's posts. Click here to go back to viewing the entire thread.
Not open for further replies.