案例一
class SingleTon { private static SingleTon singleTon = new SingleTon(); public static int count1; public static int count2 = 0; private SingleTon() { // 下面 ++ 之前, count1、count2 都是零值(默认)【准备阶段】 count1++; count2++; // 此时 count1 == 1、count2 == 1, 但并还没到【初始化阶段】, 因为现在还在执行第一条 static 语句的过程中 } public void fun() { count2++; } public static SingleTon getInstance() { return singleTon; } } public class Test { public static void main(String[] args) { SingleTon singleTon = SingleTon.getInstance(); // new 完了后 // count1 == 1: 因为它没有初始化阶段用户给的赋值, 所以保持不变还是 1 // count2 == 0: 因为按顺序下来, 初始化 count2, 赋值用户定义的 0 给它 System.out.println("count1=" + singleTon.count1); System.out.println("count2=" + singleTon.count2); singleTon.fun(); // 因为已经初始化过了 System.out.println("count2=" + singleTon.count2); } }
输出结果
count1=1 count2=0 count2=1
案例二
class SingleTon { public static int count1; public static int count2 = 0; // 这就是为什么在案例一中说注意这条的顺序, 因为在执行它之前上面已经初始化完毕 private static SingleTon singleTon = new SingleTon(); private SingleTon() { count1++; count2++; } public void fun() { count2++; } public static SingleTon getInstance() { return singleTon; } } public class Test { public static void main(String[] args) { SingleTon singleTon = SingleTon.getInstance(); System.out.println("count1=" + singleTon.count1); System.out.println("count2=" + singleTon.count2); singleTon.fun(); System.out.println("count2=" + singleTon.count2); } }
输出结果
count1=1 count2=1 count2=2
案例三
class SingleTon { public static int count1; public static int count2 = 0; private static SingleTon singleTon = new SingleTon(); private SingleTon() { count1++; count2++; } public void fun() { count2++; } public static SingleTon getInstance() { return singleTon; } } public class Test { public static void main(String[] args) { // 没想到不会报 NPE 吧, 因为 static 属于类定义, 所以也只是借此调用 SingleTon singleTon = null; System.out.println("count1=" + singleTon.count1); System.out.println("count2=" + singleTon.count2); } }
输出结果
count1=1 count2=1