单例模式确保一个类只有一个实例并提供全局访问点,常用于资源管理、配置管理、日志管理等场景;其优点包括节省资源、全局访问和控制实例数量,缺点有违反单一职责、可测试性差和并发问题;实现方式包括饿汉式、懒汉式、双重检查锁、静态内部类和枚举,其中静态内部类和枚举方式更推荐,枚举还能防止反射和序列化破坏;与静态类相比,单例可实现接口和继承,而静态类仅提供静态方法。

单例模式的核心在于确保一个类只有一个实例,并提供一个全局访问点。这在管理资源、配置信息等方面非常有用。
解决方案:
实现单例模式有几种常见方法,各有优缺点。
饿汉式: 类加载时就创建实例,线程安全,但可能造成资源浪费。
public class Singleton {
private static final Singleton instance = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return instance;
}
}懒汉式: 第一次使用时才创建实例,可以延迟加载,但线程不安全。
public class Singleton {
private static Singleton instance;
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}解决线程安全问题可以使用
synchronized
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}双重检查锁(DCL): 结合了懒汉式的延迟加载和线程安全,是一种比较常用的方式。
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;
}
}volatile
静态内部类: 利用类加载机制保证线程安全,同时实现延迟加载。
public class Singleton {
private Singleton() {}
private static class SingletonHolder {
private static final Singleton instance = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.instance;
}
}这种方式是推荐的单例模式实现方式,简洁且高效。
枚举: 最简洁的单例模式实现方式,线程安全,防止反射攻击和序列化问题。
public enum Singleton {
INSTANCE;
public void doSomething() {
// ...
}
}使用时直接
Singleton.INSTANCE.doSomething();
bee餐饮点餐外卖小程序是针对餐饮行业推出的一套完整的餐饮解决方案,实现了用户在线点餐下单、外卖、叫号排队、支付、配送等功能,完美的使餐饮行业更高效便捷!功能演示:1、桌号管理登录后台,左侧菜单 “桌号管理”,添加并管理你的桌号信息,添加以后在列表你将可以看到 ID 和 密钥,这两个数据用来生成桌子的二维码2、生成桌子二维码例如上面的ID为 308,密钥为 d3PiIY,那么现在去左侧菜单微信设置
1
单例模式有哪些应用场景?
单例模式常用于以下场景:
单例模式的优缺点是什么?
优点:
缺点:
如何防止单例模式被反射破坏?
反射可以绕过私有构造函数,创建多个实例,破坏单例模式。
在构造函数中判断: 在构造函数中判断是否已经存在实例,如果存在则抛出异常。
public class Singleton {
private static Singleton instance;
private Singleton() {
if (instance != null) {
throw new IllegalStateException("Singleton instance already exists.");
}
}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}使用枚举: 枚举天生防止反射攻击,是实现单例模式的最佳方式之一。
单例模式和静态类的区别是什么?
getInstance()
选择哪种方式取决于具体需求。如果需要保持状态、实现接口或被继承,则选择单例模式。如果只需要提供一些静态方法,则选择静态类。
以上就是如何实现一个单例模式?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号