懒汉式
/**
* 线程安全的单例模式之懒汉式
* @author love
*
*/
class Singleton{
//构造方法私有,不允许创建对象
private Singleton() {}
private static Singleton instance = null;
public static Singleton getInstance() {
if(instance == null) {
synchronized(Singleton.class){
if(instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
饿汉式
/**
* 线程安全的单例模式之饿汉式
* @author love
*
*/
class Singleton{
//构造方法私有,不允许创建对象
private Singleton() {}
private static Singleton instance = new Singleton();
public static Singleton getInstance() {
return instance;
}
}