1、饿汉模式:在类被加载的时候创建实例(线程安全的)。
2、懒汉模式:在方法被运行的时候创建实例(线程不安全的) 解决方法:通过双层校验。
饿汉模式:
public class Singleton {
//饿汉模式
//将构造函数私有化
private Singleton(){
}
//将对象实例化
private static Singleton instance = new Singleton();
//得到实例的方法
public static Singleton getInstance() {
return instance;
}
}
懒汉模式:
public class Singleton {
//懒汉模式
//将构造函数私有化
private Singleton(){
}
//将对象实例化
private static volatile Singleton instance ;
//得到实例的方法
public static Singleton getInstance() {
if(instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}