必会手撸代码
单例模式
饿汉模式
/**
* 单列--饿汉式
* 优点: 写法简单 缺点:如果该类未被使用,会一直存在 浪费内存空间
* @Date: 2021/9/18 0018 下午 17:17
* @Version: 1.0
*/
public class SingleHungry {
private static SingleHungry single = new SingleHungry();
private SingleHungry() {
}
private static SingleHungry getInstance(){
return single;
}
}
懒汉模式
/**
* 单列--懒汉式
* 优点: 需要使用过的时候创建 缺点:节约空间
* @Date: 2021/9/18 0018 下午 17:17
* @Version: 1.0
*/
public class SingleLazy {
private static SingleLazy single;
private SingleLazy() {
}
private static SingleLazy getInstance(){
if (single == null){
single = new SingleLazy();
}
return single;
}
}
懒汉模式(线程安全、同步锁)
/**
* 单列--懒汉式(线程安全)
* 优点: 线程安全,同步执行
* @Date: 2021/9/18 0018 下午 17:17
* @Version: 1.0
*/
public class SingleSafe {
private static SingleSafe single;
private SingleSafe() {
}
private static SingleSafe getInstance(){
if (single == null){
synchronized (SingleSafe.class){
single = new SingleSafe();
}
}
return single;
}
}
懒汉模式(双重线程)
/**
* 单列--懒汉式(双重线程安全)
* 优点: 线程安全,延迟加载
* @Date: 2021/9/18 0018 下午 17:17
* @Version: 1.0
*/
public class SingleDoubleSafe {
private static SingleDoubleSafe single;
private SingleDoubleSafe() {
}
private static SingleDoubleSafe getInstance(){
if (single == null){
synchronized (SingleDoubleSafe.class){
if (single == null) {
single = new SingleDoubleSafe();
}
}
}
return single;
}
}
双重线程的懒汉模式有替代方案也可以实现同样的方案(静态内部类)
/**
* 静态内部类
* @Description:
* @Date: 2021/9/18 0018 下午 17:53
* @Version: 1.0
*/
public class InsideClass {
public InsideClass() {
}
private static class SingleInsideClass{
static final InsideClass INSIDE_CLASS = new InsideClass();
}
public static InsideClass getInstance() {
return SingleInsideClass.INSIDE_CLASS;
}
}