package com.jadyer.classloader;/** * 深入JVM之號稱世界上所有Java程式員都會犯的一個錯誤 * @author 宏宇 * @editor Jan 24, 2012 7:49:18 PM * @see 這是一個很無恥的面試題,多麼卑鄙的人才能寫出這種自己給自己找麻煩的代碼啊~~ */public class ClassLoadTest {public static void main(String[] args) {SingletonFront singletonFront = SingletonFront.getInstance();System.out.println("counter11 = " + singletonFront.counter11);System.out.println("counter22 = " + singletonFront.counter22);System.out.println("=============");SingletonBack singletonBack = SingletonBack.getInstance();System.out.println("counter33 = " + singletonBack.counter33);System.out.println("counter44 = " + singletonBack.counter44);}}/** * 單例類:在變數之前new的執行個體 * @see Step01:為靜態變數分配記憶體並初始化為預設值 * @see singletonFront=null,counter11=0,counter22=0 * @see Step02:為靜態變數賦正確的初始值,並初始化類的執行個體 * @see singletonFront=new SingletonFront(),counter11=1,counter22先因為構造方法等於壹之後又因為初始值等於零 */class SingletonFront{private static SingletonFront singletonFront = new SingletonFront(); //注意這個位置public static int counter11;public static int counter22 = 0;private SingletonFront(){counter11++;counter22++;}public static SingletonFront getInstance(){return singletonFront;}}/** * 單例類:在變數之後new的執行個體 * @see Step01:為靜態變數分配記憶體並初始化為預設值 * @see counter11=0,counter22=0,singletonFront=null * @see Step02:為靜態變數賦正確的初始值,並初始化類的執行個體 * @see counter11與counter22都是先等於零之後又因為構造方法才等於壹,singletonFront=new SingletonFront() */class SingletonBack{public static int counter33;public static int counter44 = 0;private static SingletonBack singletonBack = new SingletonBack(); //注意這個位置private SingletonBack(){counter33++;counter44++;}public static SingletonBack getInstance(){return singletonBack;}}