1. 程式人生 > >寫這段程式碼的人該不該被開除?

寫這段程式碼的人該不該被開除?

class Singleton {


 private static Singleton obj = new Singleton();

 public static int counter1;

 public static int counter2 = 0;

 private Singleton() {
  counter1++;
  counter2++;
  System.out.println("constructor counter2's value :"+counter2);
 }

 public static Singleton getInstance() {
  System.out.println("getInstance counter2's value :"+counter2);
  return obj;
 }
}

public class MyMain {

 @SuppressWarnings("static-access")

 public static void main(String[] args) {

  Singleton obj = Singleton.getInstance();
  System.out.println("obj.counter1=" + obj.counter1);
  System.out.println("obj.counter2=" + obj.counter2);

  Singleton obj1 = Singleton.getInstance();
  System.out.println("obj1.counter1=" + obj1.counter1);
  System.out.println("obj1.counter2=" + obj1.counter2);
 }
}

輸出結果是:

obj.counter1=1
obj.counter2=0
obj1.counter1=1
obj1.counter2=0