设计模式-单例模式(枚举)

1. 概念

  • 保证一个类只有一个实例
  • 并为该实例提供一个全局唯一的访问节点

2. 枚举

2.1 代码示例

示例
java 复制代码
public enum Singleton08 {
    INSTANCE;

    public void sendOk(){
        System.out.println("send ok");
    }
}
java 复制代码
public class SingletonTest08 {
    public static void main(String[] args) {
        Singleton08 instance = Singleton08.INSTANCE;
        Singleton08 instance1 = Singleton08.INSTANCE;
        System.out.println(instance == instance1);
        System.out.println("instance.hashCode= " + instance.hashCode());
        System.out.println("instance1.hashCode= " + instance1.hashCode());
        instance.sendOk();
    }
}

2.2 优缺点

  1. 这借助JDK1.5中添加的枚举来实现单例模式。不仅能避免多线程同步问题,而且还能防止反序列化重新创建新的对象。
  2. 这种方式是Effective Java作者Josh Bloch提倡的方式

2.3 结论

  • 在实际开发中,推荐使用这种单例设计模式。

相关推荐
geovindu15 小时前
go: Strategy Pattern
开发语言·设计模式·golang·策略模式
嵌入式学习_force20 小时前
02_state
设计模式·蓝牙
qcx231 天前
Warp源码深度解析(七):Token预算策略——双轨计费、上下文溢出与摘要压缩
人工智能·设计模式·rust·wrap
Cosolar2 天前
提示词工程面试题系列 - Zero-Shot Prompting 和 Few-Shot Prompting 的核心区别是什么?
人工智能·设计模式·架构
geovindu2 天前
go:Template Method Pattern
开发语言·后端·设计模式·golang·模板方法模式
钝挫力PROGRAMER2 天前
贫血模型的改进
java·开发语言·设计模式·架构
qcx232 天前
Warp源码深度解析(二):自研GPU UI框架——WarpUI的ECH模式与渲染管线
人工智能·ui·设计模式·rust
likerhood2 天前
单例模式详细讲解(java)
java·开发语言·单例模式
qcx232 天前
Warp源码深度解析(三):Block-Based终端引擎——Grid模型、PTY与Shell Integration
人工智能·设计模式·架构·wrap
mounter6252 天前
Linux Kernel Design Patterns (Part 2):从经典链表到现代 XArray,拆解内核复杂数据结构的设计哲学
linux·数据结构·链表·设计模式·内存管理·kernel