单例模式
// 懒汉式(懒加载,延迟加载)
// 第一次调用getInst()方法时,对象被创建,程序结束后释放
public class Singleton {
private Singleton() {
}
private static Singleton inst = null;
public static Singleton getInst() {
if (null == inst) {
inst = new Singleton();
}
return inst;
}
}
// 饿汉式
//类被加载后,对象被创建,程序结束后释放
public class Singleton {
private Singleton() {
}
private static Singleton inst = new Singleton();
public static Singleton getInst() {
return inst;
}
}
// 懒汉式(懒加载,延迟加载)
// 双重锁定检查 实现线程安全
public class Singleton {
// 拒绝通过反射调用
private Singleton() {
if(null !=inst){
throw new RuntimeException("此类为单例模式");
}
}
//volatile关键字保证变量的唯一性
private volatile static Singleton inst = null;
public static Singleton getInst() {
if (null == inst) {
synchronized (Singleton.class) {
if (null == inst) {
inst = new Singleton();
}
}
}
return inst;
}
}