设计模式--单例模式--饿汉、懒汉、方法锁、类锁(双判断)和静态内部类模式

1、饿汉

/**
 * 饿汉式
 */
public class Singleton {

    private static Singleton instance = new Singleton();//实在饿的慌,先吃了(先创建实例)

    private Singleton(){}

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

2、懒汉

/**
 * 懒汉式
 */
public class Singleton {

    private static Singleton instance;//我还不饿,先不吃(不创建实例)

    private Singleton(){}

    public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();//这会儿我饿了,我吃(需要时创建实例)
        }
        return instance;
    }
}

3、方法锁

/**
 * 懒汉式(synchronized 方发锁 )线程安全,人云效率低
 */
public class Singleton {

    private static Singleton instance;

    private Singleton(){}

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

4、类锁(双判断)

/**
 * 双重判断 类锁 synchronized (Singleton.class) 线程安全 效率高
 */
public class Singleton {

    private static Singleton instance = null;

    private Singleton() {
    }

    public static Singleton getInstance() {
        if (instance == null) {//一次判断
            synchronized (Singleton.class) {//锁
                if (instance == null) {//二次判断
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

5、静态内部类

/**
 * 静态内部类单例模式,线程安全?
 */
public class Singleton {

    private Singleton(){}

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

    /**
     * 静态内部类
     */
    private static class SingletonHolder{
        private static final Singleton instance = new Singleton();//静态内部类内部实例化
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章