java设计模式之单例模式

来源:互联网 发布:ios算法面试题及答案 编辑:程序博客网 时间:2024/06/07 00:48

单例模式在日常开发中是一个用的比较多的模式,一般用于不允许创建多个对象时使用,单例模式的写法比较简单,但有一点需要注意的就是,注意防止线程安全问题的发生,我一般写单例模式一般有两种写法

  第一种,双重判断,效率稍低

  第一种: public static Singleton getInstance() {          if (singleton == null) {                synchronized (Singleton.class) {                   if (singleton == null) {                      singleton = new Singleton();                  }                }            }            return singleton;       }  
第二种: 推荐使用第二种
public class Single {        private static class Holder {           private static final Singleton INSTANCE = new Single();        }        private Single (){}        public static final Singleton getInstance() {           return Holder.INSTANCE;        }    }    



github地址为:  https://github.com/zhouwei5200/singleInstance

1 0
原创粉丝点击