`n 如何创建一个Java单例模式?

如何创建一个Java单例模式?

Clock Icon 发布时间:2026/11/5 6:39  · 

单例模式是在软件设计中一种常见的创建型模式,确保某个类只有一个实例并提供一个全局访问点。NET/" style="text-decoration: none; color: inherit;" title="NET">NET/" style="text-decoration: none; color: inherit;" title="java">java中的单例模式有多种实现方式,每种方式都有其优缺点。
一种简易实现方法是饿汉式单例。该方法在类加载时就创建一个实例。使用静态常量来引用这个实例,确保类在加载时就分配内存。示例代码如下:
```NET/" style="text-decoration: none; color: inherit;" title="NET">NET/" style="text-decoration: none; color: inherit;" title="java">javapublic class Singleton { private static final Singleton instance = new Singleton(); private Singleton() {} public static Singleton getInstance() { return instance; }}```
延迟加载可以通过懒汉式单例实现。这个方法在首次调用实例时创建它。使用同步或双重检查锁实现线程安全。示例代码如下:
```NET/" style="text-decoration: none; color: inherit;" title="NET">NET/" style="text-decoration: none; color: inherit;" title="java">javapublic class Singleton { private static Singleton instance; private Singleton() {} public static Singleton getInstance() { if (instance == null) { synchronized (Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance; }}```
静态内部类方式是另一种延迟加载方法。这种实现确保了线程安全并且在需要时才创建实例。内部类在被调用时才会加载。示例代码如下:
```NET/" style="text-decoration: none; color: inherit;" title="NET">NET/" style="text-decoration: none; color: inherit;" title="java">javapublic class Singleton { private Singleton() {} private static class SingletonHolder { private static final Singleton INSTANCE = new Singleton(); } public static Singleton getInstance() { return SingletonHolder.INSTANCE; }}```
枚举方式也是一种优雅的单例实现。NET/" style="text-decoration: none; color: inherit;" title="NET">NET/" style="text-decoration: none; color: inherit;" title="java">java中的枚举类型天然是单例且序列化安全。这样既简洁又保证了唯一路径。示例代码如下:
```NET/" style="text-decoration: none; color: inherit;" title="NET">NET/" style="text-decoration: none; color: inherit;" title="java">javapublic enum Singleton { INSTANCE;}```
在选择单例实现时,需要考虑以下因素:性能、简单性与线程安全。饿汉式适合对资源占用极小的场景,懒汉式适合资源开销较大,但创建不频繁的场合。静态内部类和枚举方式是现代开发中更为推荐的选择。
单例模式的应用非常广泛,特别是在需要控制资源的共享时。常见使用场景包括配置管理、日志记录、线程池等。选择适合的单例实现能够提高程序的性能和可维护性。

推荐文章

热门文章