一、建立一個Mytest6類和Singleton類java
public class MyTest6 { public static void main(String[] args) { Singleton singleton = Singleton.getInstance(); System.out.println("counter1:" +Singleton.counter1); System.out.println("counter2:" +Singleton.counter2); } } class Singleton{ public static int counter1 ; public static int counter2 = 0; private static Singleton singleton = new Singleton(); private Singleton(){ counter1 ++; counter2 ++; } public static Singleton getInstance(){ return singleton; } }
輸出結果函數
counter1:1 counter2:1
二、將counter2成員變量的位置移動到構造函數後面spa
public class MyTest6 { public static void main(String[] args) { Singleton singleton = Singleton.getInstance(); System.out.println("counter1:" +Singleton.counter1); System.out.println("counter2:" +Singleton.counter2); } } class Singleton{ public static int counter1 ; private static Singleton singleton = new Singleton(); private Singleton(){ counter1 ++; counter2 ++; System.out.println("Singleton counter1:" +counter1); System.out.println("Singleton counter2:" +counter2); } public static int counter2 = 0; public static Singleton getInstance(){ return singleton; } }
輸出結果以下:blog
Singleton counter1:1 Singleton counter2:1 counter1:1 counter2:0
首先Singleton singleton = Singleton.getInstance(); 是調用Singleton類的getInstance(),屬於主動調用。Singleton在準備階段,按照聲明的順序,賦予全部成員變量默認值。在初始化階段,構造函數裏couonter1和counter2的值變爲1,可是後面counter2的值又被賦值爲0。 因此打印了上面的結果。get
上面代碼中的構造函數裏counter2 ++;class
準備階段的意義:若是沒有準備階段,counter2是沒有值的,更不會有++操做