/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.racky.singleton;
/**
*
* @author racky
*/
public class Singleton {
private static Singleton obj=new Singleton();
private static int counter1;
private static int counter2=0;
private Singleton(){
System.out.println("create instance()");
counter1++;
counter2++;
System.out.println(counter1);
System.out.println(counter2);
}
public static Singleton getInstance(){
System.out.println("getInstance()");
return obj;
}
public static void main(String args[]){
Singleton obj=Singleton.getInstance();
System.out.println("counter1="+obj.counter1);
System.out.println("counter2="+obj.counter2);
}
}
请问这段代码的输出结果是什么?为什么会那样?其实结果我是知道的,就是不知道为什么,谁能帮我说说这个问题啊
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.racky.singleton;
/**
*
* @author racky
*/
public class Singleton {
private static Singleton obj=new Singleton();
private static int counter1;
private static int counter2=0;
private Singleton(){
System.out.println("create instance()");
counter1++;
counter2++;
System.out.println(counter1);
System.out.println(counter2);
}
public static Singleton getInstance(){
System.out.println("getInstance()");
return obj;
}
public static void main(String args[]){
Singleton obj=Singleton.getInstance();
System.out.println("counter1="+obj.counter1);
System.out.println("counter2="+obj.counter2);
}
}
请问这段代码的输出结果是什么?为什么会那样?其实结果我是知道的,就是不知道为什么,谁能帮我说说这个问题啊
本文通过一个具体的Singleton模式实现示例,详细解析了Singleton对象的创建过程及其静态方法getInstance的调用逻辑。文中还展示了如何在主函数中获取Singleton实例并打印计数器变量的值。
951

被折叠的 条评论
为什么被折叠?



