设计模式之注册表模式

果你需要管理一群不同類型的物件,並希望在程式中這些物件在取得時都是單例,你可以使用Register of Singleton模式。在Java中若要實現Register of Singleton模式,可以使用Reflection機制來達成:

import java.util.*;

public class SingletonRegistry {
    private static Map<String, Object> registry = 
                      new HashMap<String, Object>();

    private SingletonRegistry() {}
    
    public static Object getInstance(String classname) {
        Object singleton = registry.get(classname);

        if(singleton != null) {
            return singleton;
        }
        try {
            singleton = Class.forName(classname).newInstance();
        }
        catch(Exception e) {
            throw new RuntimeException(e);
        }
      
        registry.put(classname, singleton);
      
        return singleton;
    }
}


程式撰寫需透過SingletonRegistry的getInstance()來取得所需之物件,
SingletonRegistry維持唯一的一個註冊表,註冊表使用Map實現,若註冊表中已有所需之物件就直接傳回,從而保證透過SingletonRegistry的getInstance()所取得的都是單例。

如果是Python的話,則可以透過Introspection機制來實作
Registry of Singleton:

class SingletonRegistry:
__registry = {}

def __init__(self):
raise Singleton.__single

def getInstance(classname):
if classname in SingletonRegistry.__registry:
return SingletonRegistry.__registry[classname]
singleton = getattr(sys.modules[__name__] , classname)()
SingletonRegistry.__registry[classname] = singleton
return singleton



果不使用Reflection
或Introspection機制的話,則可以提供一個註冊方法

public class SingletonRegistry {
private static Map<String, Object> registry =
new HashMap<String, Object>();
private static Singleton instance;

private SingletonRegistry() {}

public static void register(String name, Object singleton) {
registry.put(name, singleton);
}

public static Object getInstance(String classname) {
return registry.get(classname);
}
}


註冊的時機可以是在建構物件之時,例如:

public class Some {
    public Some() {
        //...
        SingletonRegistry.register(Some.class.getName(), this);
    }
}


或者是在建構物件之後主動註冊:

Some some = new Some();
SingletonRegistry.register(Some.class.getName(), some);


這種方式的缺點是您必須在程式中有一段初始化程序,先向RegistrySingleton進行註冊, 好處是可以適用於沒有Reflection機制的語言。

也可以看看php版本的。http://www.cnblogs.com/youxin/archive/2013/05/25/3099138.html

转自:http://openhome.cc/Gossip/DesignPattern/RegistryOfSingleton.htm

原文地址:https://www.cnblogs.com/youxin/p/3191061.html