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

  • 相关阅读:
    水池问题的lua语言算法(面试题分析:我的Twitter技术面试失败了)
    grep
    hdu 4455 Substrings(计数)
    Concurrency Programming Guide 并发设计指引(二)
    ASP.NET 预编译命令(解决发布后第一次访问慢问题)
    将浏览页面变为可编辑状态
    windows系统上利用putty通过SSH连接亚马逊AWS服务器
    SQL Server2008 R2 数据库镜像实施手册(双机)SQL Server2014同样适用
    非域环境下使用证书部署数据库(SqlServer2008R2)镜像
    遇到问题---hosts不起作用问题的解决方法
  • 原文地址:https://www.cnblogs.com/youxin/p/3191061.html
Copyright © 2011-2022 走看看