Singletons with eager and lazy instantiation I've found more than one implementation of the Singleton Pattern in Java (more like 5-6). I want to know if both of the following snippets of code (written by me) are valid implementations of Singleton Pattern in Java.

//Eagerly intialization
public final class LoggerEagerSingleton {

private static final LoggerEagerSingleton logger = new LoggerEagerSingleton();

private LoggerEagerSingleton() {
}

public static LoggerEagerSingleton getInstance() {
    return logger;
}
}




//Lazy Initialization
public final class LoggerLazySingleton {

private LoggerLazySingleton() {
}

public static LoggerLazySingleton getInstance() {
    return LazyHelper.logger;
}

private static class LazyHelper {
    private static final LoggerLazySingleton logger = new LoggerLazySingleton();
}
}
The singleton pattern guarantees that only one instance of a class will be created into the application context.

So, in your code I see that:


You are create a static final class.
You declare the selfclass propertie as final: private static final LoggerEagerSingleton logger


Both of these last points are not necessary because the singleton pattern guarantees that just one will be create and nobody could be modify the unique instance of the singleton class. 

The singleton patterns suggest the following rules:


A private construct.
A Static private property of the self class.
A Static method to get the unique instance, where it create the instance if it has not been created.


 
    public class SimpleSingleton {

        private SimpleSingleton logger;

        private SimpleSingleton() {

        }

        public static SimpleSingleton getInstance() {

            if(logger == null)
                logger = new LoggerEagerSingleton();

            return logger;
        }
    }

  

As you can see the property logger is create in the static method getInstance() and no other methods give access or alter this property, and the method give you a way to get the unique instance of the class.

So if you apply these rules, your classes could be rewritten like:

public class LoggerEagerSingleton {

    private static LoggerEagerSingleton logger = null;

    private LoggerEagerSingleton() {
    }

    public static LoggerEagerSingleton getInstance() {
        if(logger == null)
            logger = new LoggerEagerSingleton();
        return logger;
    }

    //TODO: All the remain methods
    public void method A()
    {

    }

}


And it could be used as:

LoggerEagerSingleton ref = LoggerEagerSingleton.getInstance();
ref.void methodA();


But remember, a patter is a generic design that has been used to solve some issues that are common in several projects. So you can implement the pattern as it is presented or make some modifications without altering the essence of the pattern.