单例类有很多种,有饿汉式,懒汉式。其中懒汉式由于其两次判断被称为双重检测单例类。

看一段代码。

 

 1 public class StoreKeeper {
 2     /** 属性列表值. */
 3     private HashMap<String, Store> storepool = null;
 4     private HashMap<String, Long> lifepool = null;
 5     private static StoreKeeper instance;
 6     private StoreKeeper(){
 7         storepool = new HashMap<String, Store>();
 8         lifepool = new HashMap<String, Long>();
 9     }
10     public static StoreKeeper getInstance(){
11         if (instance == null) {
12             synchronized (StoreKeeper.class) {
13                 if (instance == null) {
14                     instance = new StoreKeeper();
15                 }
16             }
17         }
18         return instance;
19     }
View Code

相关文章: