Singleton班级:当我的主要功能在那个Singleton课内时,我能够多次拨打私人构造函数
请在下面查看我的代码。 我的疑问是: 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论