懒汉,线程不安全:
/**
* @Description: 线程不安全的懒汉式
* @CreateDate: 2021/4/8 18:04
*/
public class LanHan {
private static LanHan instance;
/*** @description 私有构造器 @date: 2021/4/8 18:07*/
private LanHan() {
}
/*** @description 延时加载,时间换空间
* 线程不安全
* @date: 2021/4/8 18:07*/
public static LanHan getInstance() {
if (instance == null) {
instance = new LanHan();
}
return instance;
}
}
懒汉,线程安全
/**
* @Description: 线程安全的懒汉式
* @CreateDate: 2021/4/8 18:04
*/
public class LanHanSyn {
private static LanHanSyn instance;
/*** @description 私有构造器 @date: 2021/4/8 18:07*/
private LanHanSyn() {
}
/*** @description 延时加载,时间换空间
* 线程安全,但是效率低下,大部分情况下,不需要去验证同步
* @date: 2021/4/8 18:07*/
public static synchronized LanHanSyn getInstance() {
if (instance == null) {
instance = new LanHanSyn();
}
return instance;
}
}```
饿汉
```java
/**
* @Description: 饿汉式
* @CreateDate: 2021/4/9 14:34
*/
public class EHan {
/*** @description 类装载时机会初始化。空间换时间 @date: 2021/4/9 14:37*/
private static EHan instance = new EHan();
private EHan() {
}
public EHan getInstance() {
return instance;
}
}
饿汉 静态
/**
* @Description: 饿汉式 静态
* @CreateDate: 2021/4/9 14:34
*/
public class EHanSt {
private static EHanSt instance;
/*** @description 类装载时机会初始化。空间换时间 @date: 2021/4/9 14:37*/
static {
instance = new EHanSt();
}
private EHanSt() {
}
public EHanSt getInstance() {
return instance;
}
}
静态内部类
/**
* @Description: java类作用描述
* @CreateDate: 2021/4/9 15:26
*/
public class StaticInner {
/*** @description 内部类,当调用的时候才会初始化 @date: 2021/4/9 15:39*/
private static class Inner {
private static final StaticInner instance = new StaticInner();
}
private StaticInner() {
}
/*** @description 调用时会加载初始化内部类,延时加载 @date: 2021/4/9 16:20*/
public static final StaticInner getInstance() {
return Inner.instance;
}
}
枚举
/**
* @Description: 枚举本身就是单例,不能延时加载
* @CreateDate: 2021/4/9 16:23
*/
public enum EnumSingleton {
/*** @description 枚举就是单例 @date: 2021/4/9 16:35*/
instance;
/*** @description 别的方法 @date: 2021/4/9 16:37*/
public void otherMethod(){}
}
校验锁
/**
* @Description: java类作用描述
* @CreateDate: 2021/4/12 15:33
*/
public class Volatile {
private volatile static Volatile instance;
private Volatile() {
}
public static Volatile getInstance() {
if (instance == null) {
synchronized (Volatile.class) {
if (instance == null) {
instance = new Volatile();
}
}
}
return instance;
}
}