美文网首页
单例设计模式

单例设计模式

作者: myserendipit | 来源:发表于2016-05-10 18:06 被阅读40次

    单例设计模式

    package design.zhc.com.designpattern.singleton;
    
    /**
     * Created by ZHC on 2016/5/3.
     */
    public class Singleton {
    
        private static Singleton singleton;
    
        private Singleton() {
        }
    
        /**
         * 懒汉模式
         * 优点:单例只有在使用的时候才实例化,一定程度上节约资源
         * 缺点:最大问题是每次调用getInstance方法都需要同步
         *
         * @return Singleton
         */
        public static synchronized Singleton getInstance() {
            if (singleton == null) {
                singleton = new Singleton();
            }
            return singleton;
        }
    
        /**
         * Double Check Lock(DCL)实现单例
         * 第一次判空为了避免不必要的同步
         *
         * @return Singleton
         */
        public static Singleton getInstance2() {
            // 第一次判空为了避免不必要的同步
            if (singleton == null) {
                synchronized (Singleton.class) {
                    if (singleton == null) {
                        singleton = new Singleton();
                    }
                }
            }
    
            return singleton;
        }
    
        /**
         * 静态内部类单例模式
         *
         * 最佳方案
         */
        public static Singleton getInstance3() {
            return SingletonHolder.sInstance;
        }
    
        private static class SingletonHolder {
            private static final Singleton sInstance = new Singleton();
        }
    }
    
    

    相关文章

      网友评论

          本文标题:单例设计模式

          本文链接:https://www.haomeiwen.com/subject/mruyrttx.html