//1.懒汉式
//1)通过内部类的方式实现
public class Singleton {
private static class instanceHolder{
private static Singleton instance = new Singleton();
};
private Singleton() {}
public Singleton getInstance() {
return instanceHolder.instance;
}
}
//2)synchronized二重check实现
public class Singleton {
private static Singleton instance = null;
private Singleton(){}
public Singleton getInstance() {
if(instance==null) {
synchronized (Singleton.class) {
if(instance==null) {
instance = new Singleton();
}
}
}
return instance;
}
}
//3)直接synchronized同步方法实现
public class Singleton {
private static Singleton instance = null;
private Singleton() {}
public synchronized Singleton getInstance() {
if(instance==null) {
instance = new Singleton();
}
return instance;
}
}
//2.饿汉式
//1)通过内部类的方式实现
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton() {}
public Singleton getInstance() {
return instance;
}
}