Java Class 如何实现单例模式

发布时间:2025-01-22 10:38:32 作者:小樊
来源:亿速云 阅读:91

在Java中,有多种方法可以实现单例模式。以下是两种常见的方法:

  1. 懒汉式(Lazy Initialization):
public class Singleton {
    // 使用volatile关键字确保多线程环境下的正确性
    private static volatile Singleton instance;

    // 将构造方法设为私有,防止外部实例化
    private Singleton() {
        // 防止通过反射创建多个实例
        if (instance != null) {
            throw new RuntimeException("Use getInstance() method to get the single instance of this class.");
        }
    }

    // 提供一个静态方法来获取唯一的实例
    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}
  1. 饿汉式(Eager Initialization):
public class Singleton {
    // 使用volatile关键字确保多线程环境下的正确性
    private static final Singleton instance = new Singleton();

    // 将构造方法设为私有,防止外部实例化
    private Singleton() {
        // 防止通过反射创建多个实例
        if (instance != null) {
            throw new RuntimeException("Use getInstance() method to get the single instance of this class.");
        }
    }

    // 提供一个静态方法来获取唯一的实例
    public static Singleton getInstance() {
        return instance;
    }
}

这两种方法都可以实现单例模式,但各有优缺点。懒汉式在第一次调用getInstance()方法时才创建实例,节省资源,但在多线程环境下需要同步。饿汉式在类加载时就创建实例,不占用资源,但可能会浪费内存。根据具体需求选择合适的方法。

推荐阅读:
  1. java单例模式的4种实现方法
  2. java如何实现单例模式

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java

上一篇:Java Class 如何实现多态

下一篇:Java Class 的序列化是如何进行的

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》