87
  1. When and how should we use a constructor

    Foo bar = new Foo();
    
  2. And when and how should we use getInstance() (static factory methods)

    Foo bar = Foo.getInstance();
    

What is the difference between these two? I have always used a constructor, but when should I use getInstance() instead?

sam1370
  • 335
  • 2
  • 18
zengr
  • 38,346
  • 37
  • 130
  • 192
  • Are you writing the class yourself? If not, what are you calling that provides it? – Chris B. Jul 02 '10 at 22:08
  • so, the implementation of the class itself means I am implementing singleton pattern, right? – zengr Jul 02 '10 at 22:11
  • Are you _calling_ `getInstance()`, or are you _writing a method_ called `getInstance()`? – Chris B. Jul 02 '10 at 22:23
  • 1
    If the question is about *constructor vs static factory methods*, I suggest to clarify and to change the title. – Pascal Thivent Jul 02 '10 at 23:18
  • @zengr: concerning your update2, this could be because you did not name your static method according to convention, which dictates that it should be named `Foo.newInstance()`. `Foo.getInstance()` is a convention for obtaining the singleton instance of a class. You should correct your example and use `Foo.newInstance()` instead. – JRL Jul 03 '10 at 00:46
  • @JRL Well, Joshua Bloch mentions some *common* names for static factory methods in Effective Java: `valueOf`, `of`, `getInstance`, `newInstance`, `getType`, `newType`. Clearly, there is no unique convention (and also no restriction on `getInstance`, even if tend to agree that it can be confusing). – Pascal Thivent Jul 03 '10 at 01:42
  • You should not add new questions as edits to the old question. – Keith Pinson Mar 20 '13 at 15:58
  • I think the question `What do you guys mean by overusing singleton?` is very much in context to the original question. – zengr Mar 20 '13 at 16:57
  • "Overuse of the Singleton pattern" merely means that programmers who are not used to object-oriented programming may be tempted to put a lot of programming there rather than using classes and objects (instances). In the same way programmers not used to OOP may be attracted to overusing static methods. – Basil Bourque Aug 01 '13 at 18:38
  • As for naming convention, I suggest Java programmers adopt the Objective-C convention of "sharedInstance" for getting a Singleton. Use "newInstance" for Factory method doing instantiation. I dislike "getInstance" because it collides with the JavaBeans property convention. – Basil Bourque Aug 01 '13 at 18:43

6 Answers6

102

Everybody seems to focus on singletons while I think that the question is actually about constructor vs static factory methods.

This is actually Item 1: Consider static factory methods instead of constructors of Effective Java by Joshua Bloch:

Item 1: Consider static factory methods instead of constructors

The normal way for a class to allow a client to obtain an instance of itself is to provide a public constructor. There is another technique that should be a part of every programmer’s toolkit. A class can provide a public static factory method, which is simply a static method that returns an instance of the class. Here’s a simple example from Boolean (the boxed primitive class for the primitive type boolean). This method translates a boolean primitive value into a Boolean object reference:

public static Boolean valueOf(boolean b) {
    return b ? Boolean.TRUE : Boolean.FALSE;
}

Note that a static factory method is not the same as the Factory Method pattern from Design Patterns [Gamma95, p. 107]. The static factory method described in this item has no direct equivalent in Design Patterns.

A class can provide its clients with static factory methods instead of, or in addition to, constructors. Providing a static factory method instead of a public constructor has both advantages and disadvantages.

Advantages (quoting the book):

  • One advantage of static factory methods is that, unlike constructors, they have names.
  • A second advantage of static factory methods is that, unlike constructors, they are not required to create a new object each time they’re invoked.
  • A third advantage of static factory methods is that, unlike constructors, they can return an object of any subtype of their return type.
  • A fourth advantage of static factory methods is that they reduce the verbosity of creating parameterized type instances.

Disadvantages (still quoting the book):

  • The main disadvantage of providing only static factory methods is that classes without public or protected constructors cannot be subclassed.
  • A second disadvantage of static factory methods is that they are not readily distinguishable from other static methods.
Pascal Thivent
  • 562,542
  • 136
  • 1,062
  • 1,124
  • 8
    The last one can be mitigated somewhat. I tend to have a static inner class called Factory and various newInstance methods in it to make it clearer when I create factory methods. It has saved me hunting around time in the past. :) – Rich Schuler Jul 03 '10 at 02:24
  • @Qberticus the inner class dedicated for factory methods is a nice idea. I'll try it, thx. – Dave O. Jul 03 '10 at 05:14
  • Certainly classes' constructors must be at least `protected` to allow subclassing, but does client code get any real advantage from making a new object and calling its constructor, versus calling a static factory method? It seems to me that a chained constructor call is semantically an instance method, while the sequence "create unitialized object and call its constructor" is semantically equivalent to a static factory method call. – supercat Jan 29 '14 at 18:42
9

You've got two questions: when should I call a getInstance() method, and when should I create one?

If you're deciding whether to call a getInstance() method, it's easy. You just need to read the class documentation to find out when you should call it. For example, NumberFormat provides a constructor and a getInstance() method; the getInstance() method will give you a localized NumberFormat. For Calendar, on the other hand, the constructor is protected. You have to call getInstance() to get one.

If you're deciding whether to create a getInstance() method, you need to decide what you're trying to accomplish. Either you don't want people to call your constructor (you're creating a singleton or a factory), or you don't mind (as in NumberFormat above, where they're initializing some objects for the convenience of the caller).


Long story short? Don't worry about creating getInstance() methods in your own code. If the time arises when they'll be useful, you'll know. And in general, if you can call a class's constructor, you're probably supposed to be doing that, even if the class provides a getInstance() method.

Chris B.
  • 85,731
  • 25
  • 98
  • 139
7

The uses for getInstance methods:

But most of the time your object will be a simple POJO and usage of public constructors is most practical and obvious solution.

U1: getInstance From Another Class

To return an instance of a different class:

public class FooFactory {
    public static Foo getInstance() {
        return new Foo();
    }
}

NumberFormat.getInstance methods do this as they actually return instances of DecimalFormat.

U2: Singleton Problems

The singleton pattern restricts many of the benefits of object oriented programming. Singletons generally have private constructors, therefore you cannot extend them. As you will be accessing it via its getInstance method and not referencing any interface, you will not be able to swap it out for another implementation.

krock
  • 28,904
  • 13
  • 79
  • 85
  • in the case of a factory pattern another method name like 'createInstance' or 'buildInstance' would be a much better fit, but still a possible case of what the asker might want (sounds still a bit neboulous and like some homework to me) – jdehaan Jul 02 '10 at 22:24
6

If you can use both then it sound like a poorly implemented singleton pattern.

Use the second option if you intend to have only one single instance of the class in your system and make the constructor private then.

Use the first to allow building several objects of the class.

BUT do not give your class the both possibilities.

Take care not to over-use singletons, only use them if really only one instance shall exist in the system otherwise you would limit the possibilities of re-use of your class in other projects. It sounds interesting to be able to call getInstance from everywhere in your project but that makes unclear who actually owns that instance: nobody and/or all. If you have a lot of singletons in a project you can bet that the system is poorly designed (usually). Singletons should be used with care, the same advice than for global variables apply.

jdehaan
  • 19,700
  • 6
  • 57
  • 97
1

One case in which I always prefer a static factory over a regular constructor is when I know the object construction will be slowish. I do simple initialization on constructor, but if I need to create something heavy I'll use a static method and document the behavior.

Guu
  • 911
  • 1
  • 9
  • 14
0

Singletons are evil. The problems I've seen surrounding it are not about re-use or extendability of a system (although I could see how that could occur), more so that I can't count the number of times i've seen obscure bugs in a system that arise from singletons.

If you do need to use a singleton, ensure it's scope is extremely narrow, i.e. judiciously limit the number of other objects in your system that know about it.

rupjones
  • 111
  • 4