Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton – the proper way

Tags:

java

singleton

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.

like image 412
q0987 Avatar asked Apr 20 '11 19:04

q0987


1 Answers

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.

like image 190
Travis Webb Avatar answered Nov 17 '22 12:11

Travis Webb