zoukankan      html  css  js  c++  java
  • 设计模式之注册表模式

    果你需要管理一群不同類型的物件,並希望在程式中這些物件在取得時都是單例,你可以使用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

  • 相关阅读:
    基于OWin的Web服务器Katana发布版本3
    如何在.NET上处理二维码
    .NET开源OpenID和OAuth解决方案Thinktecture IdentityServer
    ASP.NET Identity V2
    Azure Redis Cache
    CentOS 7 安装RabbitMQ 3.3
    ASP.Net MVC 5 in Xamarin Studio 5.2
    Centos 7.0 安装Mono 3.4 和 Jexus 5.6
    CentOS下GPT分区(转)
    CentOS下使用LVM进行分区(转)
  • 原文地址:https://www.cnblogs.com/youxin/p/3191061.html
Copyright © 2011-2022 走看看