A single design pattern type and lazy ruffian formula
Formula lazy loading when the class is not initialized, lazy loading. (Profile)
Hungry Chinese-style class loader is initialized at the load slow, fast target acquisition.
Hungry Chinese-style thread-safe,
Lazy man's need to add synchronized, otherwise unsafe.
Second, the hungry man style
1 public class Singletonehan { 2 private static Singletonehan singleton=new Singletonehan(); 3 private Singletonehan() { 4 } 5 public static Singletonehan getInstance(){ 6 return singleton; 7 } 8 9 @Override 10 public String toString() { 11 return "Singletonehan{}"; 12 } 13 }
test
1 public class testehan { 2 public static void main(String[] args) { 3 Singletonehan singletonehan = Singletonehan.getInstance(); 4 System.out.println(singletonehan); 5 } 6 }
Third, lazy style
1 public class Singletonlanhan { 2 // private static Singletonlanhan singleton=new Singletonlanhan(); 3 private static Singletonlanhan singleton=null; 4 5 private Singletonlanhan() { 6 } 7 8 public static Singletonlanhan getInstance() { 9 if (singleton == null) { 10 singleton = new Singletonlanhan(); 11 } 12 return singleton; 13 } 14 15 @Override 16 public String toString() { 17 return "Singletonlanhan{}"; 18 } 19 }
test
1 public class test { 2 public static void main(String[] args) { 3 Singletonlanhan singletonlanhan = Singletonlanhan.getInstance(); 4 System.out.println(singletonlanhan); 5 } 6 }
result
Singletonlanhan{}
Process finished with exit code 0
After the lazy supplement plus synchronized
1 public class Singletonlanhan { 2 // private static Singletonlanhan singleton=new Singletonlanhan(); 3 private static Singletonlanhan singleton=null; 4 5 private Singletonlanhan() { 6 } 7 8 public synchronized static Singletonlanhan getInstance() { 9 if (singleton == null) { 10 singleton = new Singletonlanhan(); 11 } 12 return singleton; 13 } 14 15 @Override 16 public String toString() { 17 return "锁Singletonlanhan{}"; 18 } 19 }
result
锁Singletonlanhan{}
Process finished with exit code 0