单例模式
概念:某个类在整个系统中只能有一个实例对象,并且是自己创建的唯一实例,构造方法私有化。
饿汉式:直接创建对象,不存在线程安全问题
- 直接实例化饿汉式(简洁直观)
- 枚举式(最简洁)
- 静态代码块饿汉式(适合复杂实例化)
懒汉式:延迟创建对象
- 线程不安全(适用于单线程)
- 线程安全(适用于多线程)
- 静态内部类形式(适用于多线程)
应用场景
- 数据库的连接池不会反复创建
- spring中⼀个单例模式besan的⽣成和使⽤
- 在我们平常的代码中需要设置全局的的⼀些属性保存
饿汉式示例代码
/**
* @ClassName: Singleton1
* @Description: 饿汉式1
* @Author 超霸
* @Date: 2021/1/24 0:30
*/
public class Singleton1 {
public static final Singleton1 instance=new Singleton1();
private Singleton1(){}
}
/*________________________分割线________________________*/
/**
* @ClassName: Singleton2
* @Description: 枚举式
* @Author 超霸
* @Date: 2021/1/24 13:03
*/
public enum Singleton2 {
INSTANCE;
public void chaoba() {
System.out.println("我是超霸");
}
}
/*________________________分割线________________________*/
/**
* @ClassName: Singleton3
* @Description: 静态代码块 饿汉式
* @Author 超霸
* @Date: 2021/1/24 13:12
*/
public class Singleton3 {
private static Singleton3 INSTANCE;
static {
//这里进行加载外部信息。可以对单例对象进行初始化
INSTANCE = new Singleton3();
}
private Singleton3() {
}
public static Singleton3 getInstance() {
return INSTANCE;
}
}
懒汉式示例代码
/**
* @ClassName: Singleton4
* @Description: 懒汉式1--线程不安全
* @Author 超霸
* @Date: 2021/1/24 13:14
*/
public class Singleton4 {
private static Singleton4 INSTANCE;
private Singleton4() {
}
public static Singleton4 getInstance() {
if (INSTANCE == null) {
INSTANCE = new Singleton4();
}
return INSTANCE;
}
}
/*________________________分割线________________________*/
/**
* @ClassName: Singleton4
* @Description: 懒汉式2--线程安全-增加synchronized同步关键字
* @Author 超霸
* @Date: 2021/1/24 13:14
*/
public class Singleton5 {
private static Singleton5 INSTANCE;
private Singleton5() {
}
public static synchronized Singleton5 getInstance() {
if (INSTANCE == null) {
INSTANCE = new Singleton5();
}
return INSTANCE;
}
}
/*________________________分割线________________________*/
/**
* @ClassName: Singleton4
* @Description: 懒汉式3--线程安全-内部类实现 内部类只有在需要的时候才会创建
* 不会随着jvm启动而创建
* @Author 超霸
* @Date: 2021/1/24 13:14
*/
public class Singleton6 {
private Singleton6() {
}
private static class SingletonHolder {
private static Singleton6 INSTANCE = new Singleton6();
}
public static Singleton6 getInstance() {
return SingletonHolder.INSTANCE;
}
}
/*________________________分割线________________________*/
/**
* @ClassName: Singleton4
* @Description: 懒汉式3--线程安全-双重锁校验
* @Author 超霸
* @Date: 2021/1/24 13:14
*/
public class Singleton7 {
private static Singleton7 INSTANCE;
private Singleton7() {
}
public static Singleton7 getInstance() {
if (INSTANCE != null) {
return INSTANCE;
}
synchronized (Singleton7.class) {
if (INSTANCE == null) {
INSTANCE = new Singleton7();
}
}
return INSTANCE;
}
}