In the Effective Java 2nd Joshua Bloch mentioned at Item4 there is new approach to implement Singletons. Simply make an enum type with one elemeny:

//Enum Singleton

public enum Elvis {

INSTANCE;

//Singleton method

public void leaveTheBuilding( ) {…}

}

//Test class

public class TestSingleton {

public static void main(){

Elvis.INSTANCE.leaveTheBuilding( );//only one object instance

}

}

References:

1. Sun Enums documents

2. Java Practice: When NOT to use enum’s

3. Wiki: Singleton pattern

4. Working With Design Patterns: Singleton

Advertisements