Java private constructor and getInstance() method. Why?

Status
Not open for further replies.

Bagheera

Ars Tribunus Angusticlavius
8,773
Subscriptor
Here's a topic I don't understand. What's the benefit of making a private constructor and a public getInstance method?

I understand why you would make the constructor private: to keep someone from instantiating a class. The correct term is "Utility class", right? The example I get is the Math class. Programmers should have access to Math.sqrt(), Math.random() and other methods, but they should never be able to write "Math myObject = new Math();"

But why make a public method getInstance()? Take the Calendar object, for example. You can't write "Calendar c = new Calendar()". You have to write "Calendar c = Calendar.getInstance()". But it has the exact same result: an object of type Calendar with a reference named "c".

Some research pointed me toward the "Factory Design Pattern," explained here. The concept is that you create multiple "getInstance" methods that return Objects with different properties based on the parameters of the method call. But couldn't you achieve the same objective with overloaded constructors?

Further research pointed me toward "Singletons", which ensure that only one instance of a class is instantiated. I can see a scenario where you'd want that. The getInstance() method checks to see if an object of that class already exists in the program. It returns null if an object exists. Couldn't you build that logic into the constructor?

I'm definitely missing something here. The paragraphs aren't arguing against getInstance methods. There to demonstrate that I've researched the topic and still don't get it. Can a friendly Arsian give me an example where a getInstance method works better than a public constructor(s)?
 

Vince-RA

Ars Praefectus
5,521
Subscriptor++
[url=http:/civis/viewtopic.php?p=25785119#p25785119:1we5xbq9 said:
Bagheera[/url]":1we5xbq9]
Further research pointed me toward "Singletons", which ensure that only one instance of a class is instantiated. I can see a scenario where you'd want that. The getInstance() method checks to see if an object of that class already exists in the program. It returns null if an object exists. Couldn't you build that logic into the constructor?

Assuming you're talking about Java or C#, no, you can't build that logic into the constructor, because they don't have explicit return values.

Code:
public class Foo {
  public Foo() {
    // do stuff
  } 
}

...

Foo f = new Foo(); // A new instance of Foo is returned to the caller - every time - no matter what you do inside the constructor
 

Bagheera

Ars Tribunus Angusticlavius
8,773
Subscriptor
Vince-RA, dlp. Thanks, I hadn't thought about that. So if you want to build a singleton, you can't use the constructor. Got it.

How about classes that permit multiple instances? Take Java's Calendar and DateFormat classes (but oddly not their GregorianCalendar and SimpleDateFormat classes). You can have any number of Calendars and DateFormats in a program. What's the logic behind making their constructors private?
 

andrewme

Senator
7,120
Subscriptor
[url=http:/civis/viewtopic.php?p=25785119#p25785119:3n4ddosj said:
Bagheera[/url]":3n4ddosj]
The getInstance() method checks to see if an object of that class already exists in the program. It returns null if an object exists.

Never seen it done that way - typically the singleton accessor returns (a reference / pointer to) the single instance to every requester. This means every requester in the process can easily access the instance without having to clutter up the code passing it around or resorting to global variables.
 

Bagheera

Ars Tribunus Angusticlavius
8,773
Subscriptor
[url=http:/civis/viewtopic.php?p=25786041#p25786041:1k2rksdf said:
andrewme[/url]":1k2rksdf]
[url=http:/civis/viewtopic.php?p=25785119#p25785119:1k2rksdf said:
Bagheera[/url]":1k2rksdf]
The getInstance() method checks to see if an object of that class already exists in the program. It returns null if an object exists.

Never seen it done that way - typically the singleton accessor returns (a reference / pointer to) the single instance to every requester. This means every requester in the process can easily access the instance without having to clutter up the code passing it around or resorting to global variables.

I think I'm following. So calling
Code:
Singleton a = Singleton.getInstance();
Singleton b = Singleton.getInstance();
Singleton c = Singleton.getInstance();

would result in three variables all pointing to the same Singleton object. The first time it's called, the getInstance method creates the new Singleton. The other times, it returns the object that already exists. That makes sense.
 
[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;
    }
 

Metasyntactic

Ars Legatus Legionis
31,808
Further research pointed me toward "Singletons", which ensure that only one instance of a class is instantiated. I can see a scenario where you'd want that. The getInstance() method checks to see if an object of that class already exists in the program. It returns null if an object exists. Couldn't you build that logic into the constructor?
Nope. it's not possible. You cannot return 'null' in a constructor. Indeed, you can't return anything.

Furthermore, if i call "new Foo" then i will *always* get an instance of the actual Foo type, and not, potentially, one of it's subclasses.

However, if i have "Foo getInstance(...)" then i can return an instance of Foo, or one of its subclasses.

I may return a GregorianFoo, or a JulianFoo. etc. etc.

Constructors (in java), have no ability to do this. Though it's potentially something that could be added to the language. We've discussed it in C#, but shied away from it as it's so different from how people think of "new" today.
 
[url=http:/civis/viewtopic.php?p=25786809#p25786809:2yaneou9 said:
Faramir[/url]":2yaneou9]It's sort of cruel to bring this up, but once you've figured out factories the next thing to try to wrap you mind around is dependency injection. Love it or hate it's what a lot of new java code is using.

Google Guice: Motivation has decent explanation.

And while we're on the topic of dependency injection, Singletons hide the dependency. I have grown to hate them more than any other misused pattern.
 
While all that has been said about singleton is true, there is an alternative, and less intrusive way of implementing singleton-ness : Monostate. This hides the ugliness of requiring your consumer to know it is a singleton.

In dependency-injection scenario, this is all taken care of by the injector implementation, but nonetheless it is a good, and IMHO more natural, alternative to your typical singleton implementation.
 

Bagheera

Ars Tribunus Angusticlavius
8,773
Subscriptor
[url=http:/civis/viewtopic.php?p=25787729#p25787729:2770d0m1 said:
Faramir[/url]":2770d0m1]I don't really know anything about certifications, but it seems very strange that they want you to take an exam on 6, when it's been completely deprecated. You can't even get oracle jvms for it anymore unless you pay for them. Not that 7 is hugely different, but why don't they assign a test for the current version?

The courses are slightly outdated. My last course was on Perl, yet there's no Python course...Either way, the test is a bitch, with a passing score of only 61%.
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
Note that the "factory" pattern (which is what the 'getInstance() stuff is) is actually one of the few patterns worthy of being described and 'taught' as a concept.

The rough idea is "I want something that can do X (or if things have gone horribly wrong in your codebase X,Y and Z) but you want people that desire such a thing to NOT take a concrete dependency on a specific type that does this, instead you want an interface (or less pleasant, and abstract class) to be all that they depend on for using it. As Meta (and others) have said, none of the main stream statically typed languages allow you to change what it got back from the new Foo() operation, it must always be *exactly* a Foo.

It's normally used in a very OO-centric way, and only makes sense with some form of polymorphism, plus it's a useful *idea* but maps so easily to a static method call it's hard to justify backing it into the language. About all you could argue for is to make it feasible to define such static methods on interfaces directly to avoid the, sometimes pointless provision of the class which hosts the factory method. That said you may end up paying quite a bit other (less user visible) areas to allow such things to be defined.

It is however badly named. Factories *make or assemble things". It might be the design of the system that it reuses them, has only one, generates one per thread, etc. etc. The important thing is that it _provides_ instances of this on request, not how, or if, it makes them (that is of interest to the implementer, not the consumer).

As such it is normally *not* a good idea to call such methods "Factory". Even if all it is is the way to get a default instance call your method GetDefaultInstance() or whatever. If you then later want a way to make ones for testing then GetTestInstance() will work.

The alternate is going full on dependency injection, which is fine if that works for you (I find it massively annoying in it's disruption of tooling), either approach has pros and cons.
 

pyu

Ars Praefectus
5,108
Subscriptor
[url=http:/civis/viewtopic.php?p=25787641#p25787641:661mp3sb said:
Bagheera[/url]":661mp3sb]Thanks for all the information. This has really helped me understand some pretty advanced concepts.

On an unrelated note, has anyone taken Oracle's Java SE 6 Programmer exam? It's the last exam I have to pass to finish my degree at Western Governor's University, and it's killing me.

My only thought is that your degree program should have insisted on the Java 7 test, since that has been out for some time and, well why not?

Other than that, I took it 3/4 years ago - it was paid for by my-then employer and they insisted on it as part of a move to 'certify' everyone - and my only advice is to get some practice on it via the various free exam kits online. To be honest, it has very little to do with writing actual programs and everything to do with thinking like the Java compiler or the JVM itself.
 
Status
Not open for further replies.