单例模式定义:
普通单例代码实现:
public class Singleton {
private static Singleton instance = new Singleton();
/* 需要将无参构造函数私有化,防止应用通过默认 new 的方式初始化实例*/
private Singleton() {
public static Singleton getInstance() {
return instance;
}
}
通常会使用懒加载
模式,即使用的时候才进行实例化:
public class Singleton {
private static Singleton instance;
private Singleton() {
}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
如果有多线程操作的情况下,就可以在if (instance == null)
环节出现问题,因为多个线程获取实例,同时调用该方法可能new
出两个不同的实例。
解决方法:
①、不使用懒加载
的机制(缺点:即时不实用该实例也进行了初始化,耗存)
②、利用synchronized
进行同步。
(缺点:每次都进行同步,大大降低了系统的性能)
③、最优方案: