java中的单例模式

来源:互联网 发布:java已过时需要更新 编辑:程序博客网 时间:2024/06/05 06:26

恶汉式

  1. public class EagerSingleton {  
  2.   
  3.     private static final EagerSingleton instance = new EagerSingleton();  
  4.   
  5.     private EagerSingleton() {  
  6.   
  7.     }  
  8.   
  9.     public static EagerSingleton getInstance() {  
  10.         return instance;  
  11.     }  
  12.   
  13. }  

懒汉式

  1. public class LazySingleton {  
  2.       
  3.     private static LazySingleton instance = null;  
  4.       
  5.     private LazySingleton() {  
  6.           
  7.     }  
  8.       
  9.     public synchronized static LazySingleton getInstance() {  
  10.         if(instance == null){  
  11.             instance = new LazySingleton();  
  12.         }  
  13.         return instance;  
  14.     }  
  15.   
  16. }  

0 0