这个是先初始化对象。 称为:饿汉式
1 class Single { 2 3 private static Single s=new Single(); 4 5 private Single(){} 6 7 public static Single getInstance() 8 9 { 10 11 return s; 12 13 } 14 15 }
//对象是方法被调用时,才被初始化,也叫做对象的延时加载。成为:懒汉式
1 class Single { 2 3 private static Single s=null; 4 5 private Single(){} 6 7 public static Single getInstace() 8 9 { 10 if(s==null) 13 { 14 s=new Single();
return s;
} 20 21 } 22 23 } 24 25 //调用 26 27 class { public static void main(string [] args) 28 29 { 30 31 System.out.println("Hello World!"); 32 33 } 34 35 }