单例模式在日常开发中是一个用的比较多的模式,一般用于不允许创建多个对象时使用,单例模式的写法比较简单,但有一点需要注意的就是,注意防止线程安全问题的发生,我一般写单例模式一般有两种写法
第一种,双重判断,效率稍低
第一种: 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