国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

Simply Singleton -- part1 By David Geary

2019-11-18 11:30:05
字體:
來源:轉載
供稿:網友

Use a registry
Use a singleton registry to:

  • Specify singleton classes at runtime
  • PRevent singleton subclasses from allowing multiple instances

Example 8 lists a singleton class that maintains a registry of singletons, registered by class name:

Example 8. A singleton with a registry

import java.util.HashMap;
import org.apache.log4j.Logger;

public class Singleton {
   private static HashMap map = new HashMap();
   private static Logger logger = Logger.getRootLogger();

   protected Singleton() {
      // Exists only to thwart instantiation
   }
   public static synchronized Singleton getInstance(String classname) {
      if(classname == null) throw new IllegalArgumentException("Illegal classname");
         Singleton singleton = (Singleton)map.get(classname);

      if(singleton != null) {
         logger.info("got singleton from map: " + singleton);
         return singleton;
      }
      if(classname.equals("SingeltonSubclass_One"))
            singleton = new SingletonSubclass_One();        
         else if(classname.equals("SingeltonSubclass_Two"))
            singleton = new SingletonSubclass_Two();

      map.put(classname, singleton);
      logger.info("created singleton: " + singleton);
      return singleton;
   }
   // Assume functionality follows that's attractive to inherit
}

The preceding base class creates subclass instances and stores them in a map. But that base class is high maintenance because you must update its getInstance() method for every subclass. LUCkily, we can use reflection to skirt that issue.

Use reflection
Example 9 lists a singleton with a registry that uses reflection to instantiate a particular class's objects. With this implementation, as opposed to Example 8, the Singleton.getInstance() method does not need to update when new subclasses are implemented.

Example 9. Use reflection to instantiate singletons


import java.util.HashMap;


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 罗源县| 靖安县| 凌云县| 洞头县| 永和县| 湄潭县| 黑龙江省| 陵川县| 元江| 阳信县| 左贡县| 营山县| 保亭| 临夏县| 苍梧县| 嘉鱼县| 海盐县| 渝中区| 波密县| 炎陵县| 怀安县| 竹北市| 四子王旗| 绥宁县| 班戈县| 邯郸县| 寿宁县| 防城港市| 昌吉市| 贺兰县| 丽江市| 德江县| 三门县| 溧阳市| 手机| 阳谷县| 长寿区| 团风县| 景洪市| 汝城县| 普陀区|