按需初始化持有者 Idiom 如何确保只有“单个”对象?实例被创建过吗?

发布于 2025-01-13 10:12:11 字数 361 浏览 2 评论 0原文

我浏览了维基 https://en.wikipedia.org/wiki/Initialization-on -demand_holder_idiom 来理解 Singleton 模式的按需持有者初始化习惯用法,尽管 wiki 提到了它如何是线程安全的,但它并没有说明这实际上如何确保只有一个实例创建过,即如果在两个不同的类中调用 Something.getInstance() 他们如何拥有相同的对象?

我是 Java 新手,所以任何帮助将不胜感激。

I went through the wiki https://en.wikipedia.org/wiki/Initialization-on-demand_holder_idiom to understand Initialization on demand holder Idiom for Singleton pattern, though the wiki mentions how it's thread safe, it doesn't say how this actually ensures only one instance is created ever, i.e if in two different classes Something.getInstance() is called how do they have the same object ?

I am new to Java, so any help would be appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

蓝色星空 2025-01-20 10:12:11

单例的基本模式:

//final so it can't be extended, not needed, but I like it for security
public final class MySingleton {
    //Private so no other class can access it directly
    //static so it stays resident in memory
    //final so it can't be nulled out or reassigned;
    //The constructor is called when the class is loaded.
    private static final MySingleton instance = new MySingleton();

    //The constructor is private so no more instances can be created
    private MySingleton() {
    }

    public static final MySingleton getInstance() {
       return instance;
    }

    //Alternatively, you could have the instance initialized to null
    //and have creation when getInstance() is called
    public static final MySingleton getIntance() {
        synchronized(instance) {
           if (instance == null) {
               instance = new MySingleton();
           }
           return instance
        }
}

Basic pattern for a singleton:

//final so it can't be extended, not needed, but I like it for security
public final class MySingleton {
    //Private so no other class can access it directly
    //static so it stays resident in memory
    //final so it can't be nulled out or reassigned;
    //The constructor is called when the class is loaded.
    private static final MySingleton instance = new MySingleton();

    //The constructor is private so no more instances can be created
    private MySingleton() {
    }

    public static final MySingleton getInstance() {
       return instance;
    }

    //Alternatively, you could have the instance initialized to null
    //and have creation when getInstance() is called
    public static final MySingleton getIntance() {
        synchronized(instance) {
           if (instance == null) {
               instance = new MySingleton();
           }
           return instance
        }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文