Appendix 2. Design Patterns

2.1. Design a class using the Singleton design pattern - Source Code

Code:

package c2.s1.eager;

/**
 * @author Mikalai Zaikin
 */
public class Singleton {

    private static final Singleton instance = new Singleton();

    // Private constructor prevents instantiation from other classes
    private Singleton() {
    }

    public static Singleton getInstance() {
        return instance;
    }
}
					

Code:

package c2.s1.enum1;

/**
 * @author Mikalai Zaikin
 */
public enum Singleton {
    INSTANCE;
}
					

Code:

package c2.s1.enum2;

/**
 * @author Mikalai Zaikin
 */
public enum Singleton {
    INSTANCE;

    public static Singleton getInstance() {
        return INSTANCE;
    }
}
					

Code:

package c2.s1.holder;

/**
 * @author Mikalai Zaikin
 */
public class Singleton {

    // Private constructor prevents instantiation from other classes
    private Singleton() {
    }

    /**
     * SingletonHolder is loaded on the first execution of Singleton.getInstance()
     * or the first access to SingletonHolder.INSTANCE, not before.
     */
    private static class SingletonHolder {
        public static final Singleton INSTANCE = new Singleton();
    }

    public static Singleton getInstance() {
        return SingletonHolder.INSTANCE;
    }
}
					

Code:

package c2.s1.lazy;

/**
 * @author Mikalai Zaikin
 */
public class Singleton {

    private static Singleton instance;

    private Singleton() {
    }

    public static synchronized Singleton getInstance() {
        if (null == instance) {
            instance = new Singleton();
        }
        return instance;
    }
}
					

Code:

package c2.s1.lazy1;

/**
 * @author Mikalai Zaikin
 */
public class Singleton {

    private static Singleton instance;

    private Singleton() {
    }

    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}
					

Professional hosting         Free 'Oracle Certified Expert Web Services Developer 6' Guide     Free SCDJWS 5.0 Guide