一、什么是单例模式
保证一个类仅有一个实例,并提供一个访问它的全局访问点。
不用重复去创建相同的对象。
二、特点
1.构造方法私有
2.自己创建一个自己的唯一实例
3.在其他时候创建时都是返回的同一个对象
三、适用场景
一些工具类,线程池等。
四、实现
1.懒汉模式:
public class SingletonLazy {
private SingletonLazy() {}
private static volatile SingletonLazy singletonLazy = null;
public SingletonLazy getInstance() {
if(singletonLazy == null) {
singletonLazy = new SingletonLazy();
}
return singletonLazy;
}
}
上面代码由于是在使用时才创建对象,所以多线程时,可能引发线程安全问题,所以需要加上同步锁。
public class SingletonLazy {
private SingletonLazy() {}
private static volatile SingletonLazy singletonLazy = null;
public SingletonLazy getInstance() {
if(singletonLazy == null) {
synchronized (SingletonLazy.class) {
if (singletonLazy==null) {
singletonLazy = new SingletonLazy();
}
}
}
return singletonLazy;
}
}
2.饿汉模式:
public class SingletonHungry {
private SingletonHungry() {}
private static volatile SingletonHungry singletonHungry = new SingletonHungry();
public SingletonHungry getInstance() {
return singletonHungry;
}
}
上面代码由于是在程序启动时就创建了对象,所以线程是安全的。