码迷,mamicode.com
首页 > 其他好文 > 详细

单例模式的代码总结

时间:2017-09-19 17:48:17      阅读:146      评论:0      收藏:0      [点我收藏+]

标签:single   代码优化   安全   ==   建议   根据   turn   pre   style   

懒汉式单例类

/**
 * 懒汉式单例类
 * 懒汉式是典型的时间换空间
 * @author MJ
 *
 */
public class LazySingleton {
    private static LazySingleton instance = null;

    // 私有构造方法
    private LazySingleton() {
    }

    // 静态工厂方法
    public static synchronized LazySingleton getInstance() {
        if (instance == null) {
            instance = new LazySingleton();
        }
        return instance;
    }
}

 

饿汉式单例类

/**
 * 饿汉式单例类
 * 饿汉式是典型的空间换时间
 * @author MJ
 *
 */
public class EagerSingleton {
    private static EagerSingleton instance = new EagerSingleton();
    
    /**
     * 私有构造方法
     */
    private EagerSingleton(){}
    
    //静态工厂方法
    public static EagerSingleton getInstance() {
        return instance;
    }
}

 

双重检查加锁

/**
 * 双重检查加锁
 * 提示:由于volatile关键字可能会屏蔽掉虚拟机中一些必要的代码优化,所以运行效率并不是很高。因此一般建议,没有特别的需要,不要使用。
 * 也就是说,虽然可以使用“双重检查加锁”机制来实现线程安全的单例,但并不建议大量采用,可以根据情况来选用。
 * 
 * @author MJ
 *
 */
public class Singleton {
    private volatile static Singleton instance = null;

    private Singleton() {
    }

    // 静态工厂方法
    public static Singleton getInstance() {
        // 先检查实例是否存在,如果不存在才进入下面的同步快
        if (instance == null) {
            // 同步块,线程安全的创建实例
            synchronized (Singleton.class) {
                // 再次检查实例是否存在,如果不存在才真正的创建实例
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

 

单例模式的代码总结

标签:single   代码优化   安全   ==   建议   根据   turn   pre   style   

原文地址:http://www.cnblogs.com/MJyc/p/7552674.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!