话不多说直接上案例!
1.饿汉式
//饿汉式
public class Singleton {
//创建私有的静态的实现类,在类加载时创建该对象
private static Singleton instance = new Singleton();
//提供无参构造方法
private Singleton() {
}
//对外暴露公共的静态的方法供外界访问
public static Singleton newInstance() {
//返回instance对象
return instance;
}
}
2.懒汉式
//懒汉式
public class Singleton {
//定义一个空的类型
private static Singleton instance = null;
//提供无参构造方法
private Singleton(){}
//对外暴露公共的静态的方法供外界访问,如果是多线程场景时添加synchronized关键字进行修饰
public static synchronized Singleton newInstance(){
//if判断instance对象是否为空
if(null == instance){
//当instance对象为空时进行创建实例对象
instance = new Singleton();
}
//返回instance对象
return instance;
}
}
3.双重锁安全验证
//双重锁安全验证
public class Singleton {
//添加volatile关键字保证instance状态的可见性
private static volatile Singleton instance = null;
//提供无参构造方法
private Singleton(){}
//对外暴露公共的静态的方法供外界访问
public static Singleton getInstance() {
//if判断instance对象是否为空
if (instance == null) {
//当instance为空时对线程进行加锁
synchronized (Singleton.class) {
//if判断instance对象是否为空
if (instance == null) {
//当instance对象为空时进行创建实例对象
instance = new Singleton();
}
}
}
//返回instance对象
return instance;
}
}