Java设计模式- Singleton

96
何恩
2014.06.15 20:37* 字数 32

Java 设计模式 单例模式 Singleton


1.懒汉(线程安全)

//懒汉
public class Singleton {
    private static Singleton singleton;

    private Singleton() {

    }

    public static synchronized Singleton getSingleton() {
        if (singleton == null) {
            singleton = new Singleton();
        }

        return singleton;
    }
}

2.饿汉

//饿汉
public class Singleton {
    private static final Singleton singleton = new Singleton();

    private Singleton () {

    }

    public static Singleton getSingleton() {
        return singleton;
    }
}

3.静态内部类

//静态内部类
public class Singleton {
    private static class SingletonHolder {
        private static final Singleton singleton = new Singleton();
    }

    private Singleton() {

    }

    public static Singleton getSingleton() {

        return SingletonHolder.singleton;
    }
}

4.枚举

//枚举
public enum Singleton {
    INSTANCE;

    public void whateverMethod() {

    }
}

5.double-lock

//double-lock
public class Singleton {
    private volatile static Singleton singleton;

    private Singleton() {

    }

    public static Singleton getSingleton() {
        if (singleton == null) {
            synchronized(Singleton.class) {
                if (singleton == null) {
                    singleton = new Singleton();
                }
            }
        }

        return singleton;
    }
}
Hello World!
Web note ad 1