public class Singleton {
/**
* 1.私有构造函数,只能在该类中new
* 2.获取单例要加锁,保证只有一个实例存在
* 3.加锁之前要判断是否为空,是为了减少频繁加锁,提高性能
*/
private Singleton() {};
private static Singleton singleton = null;
public static Singleton getSingleton() {
if (singleton == null)
{
synchronized (Singleton.class) {
if (singleton == null) {
return new Singleton();
}
}
}
return singleton;
}
}
网友评论