懒汉模式
1.构造私有
2.直接在类体中new出唯一对象,注意有可能产生线程并发问题
public class LazySingleton {
private LazySingleton() {
// TODO Auto-generated constructor stub
}
private static LazySingleton lazySingleton;
/**
* 在public中new出唯一对象
* 在方法体中创建该唯一对象有可能产生线程并发问题
* 加synchronize同步锁
*/
public static LazySingleton getInstance(){
if(lazySingleton==null){
lazySingleton = new LazySingleton();
}
return lazySingleton;
}
}
线程安全
public class Singleton {
private static Singleton instance;
private Singleton (){}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
饥汉/饿汉模式
1.构造私有
2.直接在类体new出唯一对象
3.添加public方法返回唯一对象
public class EagerSingleton {
//构造方法私有
private EagerSingleton() {
// TODO Auto-generated constructor stub
}
//new出唯一对象
private static final EagerSingleton EAGER_SINGLETON
= new EagerSingleton();
/**
* 添加public方法,让外界能够访问该唯一对象
*/
public static EagerSingleton getInstance(){
return EAGER_SINGLETON;
}
}