Singleton班级:当我的主要功能在那个Singleton课内时,我能够多次拨打私人构造函数

发布于 2025-02-11 14:53:53 字数 871 浏览 1 评论 0原文

请在下面查看我的代码。 我的疑问是: Java Singleton class 是否可以有一种主要方法 这将导致创建多个对象,因此该类不遵循单例设计模式。在Singleton类中执行主要方法应该被认为是不良的做法吗? 这是我的代码:

public class SingletonDemo {

private static int counter; //counter for number of objects
private static SingletonDemo obj;

private SingletonDemo() {
    System.out.println("Object number " + ++counter);
}

public static synchronized SingletonDemo getInstance() {
    if (obj == null) {
        obj = new SingletonDemo();
    } else {
        System.out.println("No new object created");
    }
    return obj;
}

public static void main(String[] args) {
    SingletonDemo.getInstance();
    SingletonDemo.getInstance();
    SingletonDemo.getInstance();

    SingletonDemo obj1 = new SingletonDemo();
    SingletonDemo obj2 = new SingletonDemo();
    SingletonDemo obj3 = new SingletonDemo();
}

}

Please check out my code below.
My doubt is:
Can there be a main method in java singleton class
This will result in more than one object being created so this class does not follow the Singleton design pattern. Should it be considered bad practice to execute the main method in Singleton class?
Here is my code:

public class SingletonDemo {

private static int counter; //counter for number of objects
private static SingletonDemo obj;

private SingletonDemo() {
    System.out.println("Object number " + ++counter);
}

public static synchronized SingletonDemo getInstance() {
    if (obj == null) {
        obj = new SingletonDemo();
    } else {
        System.out.println("No new object created");
    }
    return obj;
}

public static void main(String[] args) {
    SingletonDemo.getInstance();
    SingletonDemo.getInstance();
    SingletonDemo.getInstance();

    SingletonDemo obj1 = new SingletonDemo();
    SingletonDemo obj2 = new SingletonDemo();
    SingletonDemo obj3 = new SingletonDemo();
}

}

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

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文