zoukankan      html  css  js  c++  java
  • 单例模式的代码总结

    懒汉式单例类

    /**
     * 懒汉式单例类
     * 懒汉式是典型的时间换空间
     * @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;
        }
    }
  • 相关阅读:
    《Dive into Python》Study_Notes
    Python 各种应用收集
    Remotely disconnect a terminal services session
    stop the bibi
    SQL写法(累积)
    Django’s admin html editor — TinyMCE
    Djangobook note
    清除windows系统垃圾
    ubuntu下PDF乱码解决方法
    using的几种用法
  • 原文地址:https://www.cnblogs.com/MJyc/p/7552674.html
Copyright © 2011-2022 走看看