5
public enum YourSingleton {
    INSTANCE;

    public void doStuff(String stuff) {
        System.out.println("Doing " + stuff);
    }
}

YourSingleton.INSTANCE.doStuff("some stuff");

Here is the original link, http://electrotek.wordpress.com/2008/08/06/singleton-in-java-the-proper-way/

I am asking why we can call the function doStuff this way in Java.

Dante May Code
  • 11,177
  • 9
  • 49
  • 81
q0987
  • 34,938
  • 69
  • 242
  • 387
  • I found a good comment from josefx through this link http://stackoverflow.com/questions/2080681/difference-of-enum-between-java-and-c – q0987 Apr 20 '11 at 19:25
  • See also [Item 3: Enforce the Singleton Property with a Private Constructor or an enum Type](http://drdobbs.com/java/208403883?pgno=3) – trashgod Apr 20 '11 at 21:07

4 Answers4

5

In Java, enum can do everything that class can [1]. YourSingleton.INSTANCE creates an instance of YourSingleton, so you can then invoke methods as if it were a regular class instance, which it basically is.

See the official Java docs for a more in-depth discussion on Enum Types: http://download.oracle.com/javase/tutorial/java/javaOO/enum.html

[1] enum does not have a practical implementation of inheritance. Since all enum types implicity inherit java.lang.Enum and Java does not support multiple inheritance, you cannot extend anything else.

Travis Webb
  • 14,688
  • 7
  • 55
  • 109
  • @Travis-Webb YourSingleton.INSTANCE is creating a new instance each time is referenced? because in that case is not a singleton. I think is not clear for me how this is working – Dave Apr 20 '11 at 19:22
  • @Dave, please check this http://stackoverflow.com/questions/2080681/difference-of-enum-between-java-and-c – q0987 Apr 20 '11 at 19:24
  • @Dave No, all enum values are `static final` behind the scenes. – pickypg Apr 20 '11 at 19:25
  • @pickypg That makes more sense to me. Thanks! – Dave Apr 20 '11 at 19:29
2

The Traditional way to implementing singleton is fine, but to maintain its Status as true singleton, it needs to protect itself from sophisticated Serialization and Reflection Attacks. The general way of doing this, is by making the class Implement Serializable, make all instance fields Transient and also implement a readResolve method. (that return the same singleton instance).

The Enum Singleton pattern provides all these features out of the box. But the main reason, I like the Enum variant is its readability. According to me, it conveys what it does, in a much more concise fashion, than a traditional singleton.( You do not have to explain to a new developer, all the vagaries involved in serialization and how serialization might break the singleton guarantee and why you need readResolve method etc etc..)

uncaught_exceptions
  • 21,712
  • 4
  • 41
  • 48
  • 1
    I used to use interfaces to pull constants into classes, and was disabused of this behavior because, while it works, it's not the purpose of an interface. Might one be making a reasonable argument against the use of an Enum for creating singletons? Is that an abuse of Enums? – Marvo Apr 20 '11 at 19:36
  • 1
    This answer goes straight to the heart of the issue. If any of you need a reference, look at Effective Java (Bloch), item 3. http://books.google.com/books?id=ka2VUBqHiWkC&pg=PA17 – Jason S Apr 20 '11 at 19:40
  • @Marvo, the argument of abusing Enum is subjective, but according to me, using Enum for singleton does not break any usage contract. (unlike in case of Interface, in which it is used to perform something it was not designed to..) and the fact that it is superior (in ease of Impl, conciseness and readability) to other Singleton patterns makes using Enum a no-brainer. – uncaught_exceptions Apr 20 '11 at 19:48
  • @jason. I agree.. In fact, I learn about Singleton Enum Pattens from Effective Java. – uncaught_exceptions Apr 20 '11 at 19:49
  • @Marvo: I think you have it backwards. Enums can implement one or more interfaces as a singleton, but in no way would restrict an interface. – Jason S Apr 20 '11 at 19:50
  • @Jason: The interface example I used was separate from the Enum example. I'm more concerned about overloading the purpose of an Enum, though I'm definitely intrigued by the idea. I suspect that @doc_180 is correct in that it's a subjective matter, and that there will be some shops that will spank you for using this approach. – Marvo Apr 20 '11 at 20:51
0

I know this is not really what you asked for but this is what I do when I need a class to be a singleton, which may help. I create one static getInstance method that either creates and returns a new instance of the class if none exist or I return the existing reference of itself, and I make the constructor for this class private.

For example:

public class NameOfClass{
    private static NameOfClass variableReferencingThisClass=new NameOfThisClass();

    private NameOfClass(){}

    public static NameOfClass getInstance(){
        return variableReferencingThisClass;
    }
}
John Kane
  • 4,383
  • 1
  • 24
  • 42
  • No. It's not thread safe and in a multithreaded application it could result in multiple instances being created, and used. After the first group of uses, it would "settle" into being a singleton, but if anyone held onto the reference returned by `getInstance()`, then all bets are off and this "singleton" would never be a singleton or safe to use. – pickypg Apr 20 '11 at 19:30
  • I don't think it is. If possible, write "private static final NameOfClass singleton = new NameOfClass()", which then alleviates the need for a null check in getInstance(). But doc_180 elsewhere in this topic mentions "Serialization and Reflection Attacks", which is something I'd never thought about. (This solution still leaves some time where multiple constructors might be run, though, I think.) – Marvo Apr 20 '11 at 19:32
0

You can also use the double-lock singleton creation. Assuming the class is MyObject, has a private constructor, and has a declared a static field instance as null. However, this is not a guarantee that 2 singletons will not end up getting created, but is a much closer attempt to thread safety than a single check.

public static MyObject getInstance()
{
  if (instance == null)
  {
    synchronized(MyObject.class) {  
      if (instance == null)          
        instance = new MyObject(); 
    }
  }
  return instance;
}
lobster1234
  • 7,679
  • 26
  • 30
  • how is this any better than `final private static MyObject INSTANCE = createInstance(); public static MyObject getInstance() { return INSTANCE; }` – Jason S Apr 20 '11 at 22:02
  • It's better for some approaches, because it's lazy loaded.. but as noted in the answer it will fail occasionally when used in a concurrent context. – Sam May 02 '18 at 11:18