目录
1.什么是单例
单例模式是一种创建型设计模式,它的作用是在系统运行期间,保证一个类仅有一个实例对象,并提供一个全局唯一的访问点。
2.实现步骤
1.饿汉模式
/**
* @author LJL
* @version 1.0
* @title Singleton
* @date 2023/6/9 16:12
* @description 单例模式(饿汉)
*/
public class Singleton {
// 饿汉式单例模式,将实例对象在类加载时创建
private static Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}
2.懒汉模式
/**
* @author LJL
* @version 1.0
* @title Singleton
* @date 2023/6/9 16:12
* @description 单例模式(懒汉)
*/
public class Singleton {
private volatile static Singleton instance;
private Singleton() {}
//双重检查机制 避免多线程情况 创建多个实例
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
3.适用场景
-
提供了一个全局访问点,使得实例可以被其他对象访问。
4.优缺点
1.优点
(唯一)节约系统资源,提高性能
(全局)可用性高
2.缺点
线程不安全 :在多线程环境中,单例模式需要进行线程安全的处理,否则可能会导致多个线程同时访问同一个实例对象,导致数据不一致、应用程序崩溃等问题。
增加耦合度