在应用程序中保证最多只能有一个实例
public class Singleton{
// 私有化属性,防止通过类名直接调用
private static Singleton singleton;
// 私有化构造方法,防止其他类实例化这个对象
private Singleton{}
// 对外提供的访问入口
public static Singleton getInstance(){
// 如果实例化过,直接返回
if(singleton == null){
// 多线程情况下,可能会出现if同时成立的情况
// 解决方案:添加锁,但是由于添加了锁,会导致执行效率变低
synchronized(Singleton.class){
// 双重验证
if(singleton == null){
sington = new Singleton();
}
}
}
return singleton;
}
}
解决了懒汉式中多线程访问可能出现同一个对象和效率低的问题
public class Singleton{
// 在类进行加载时进行实例化
private static Singleton singleton = new Singleton();
private Singleton(){}
public static Singleton getInstance(){
return singleton;
}
}原文:https://www.cnblogs.com/chaunc3y/p/11491087.html