Lazy synchronized initialization
public final class Session { private static Session instance; /** singleton */ private Session() {} /** if you do not need synchronisation do not mark it as synchronized */ public synchronized static Session getInstance() { return (instance == null) ? instance = new Session() : instance; } /** your methods goes here... */ }
PRO: can be initialized lazy the first time it is used
CONTRA: Singletons shall be avoid because they are hard to test and debug. Futher they contribute to less cohesive designs.
No Lazy initialization needed
public class Session { private final static Session INSTANCE = new Session(); private Session() {} public static Session getInstance() { return Session.INSTANCE; } protected Object clone() { throw new CloneNotSupportedException(); } /** your methods goes here... */ }
PRO: Immediate allocation of the needed resource
CONTRA: Needs "more" resource as nescessary + CONTRA from first case
No Lazy initialization needed (the elegant, modern way)
public enum Session { INSTANCE; private int session; public int getSession() { return ++session; } /** your methods goes here... */ }
PRO: Very simple, modern way. Immediate allocation of the needed resource
CONTRA: Needs "more" resource as nescessary + CONTRA from first case