设计模式之注册表模式
2013-07-15 14:10 youxin 阅读(1250) 评论(0) 编辑 收藏 举报如果你需要管理一群不同類型的物件,並希望在程式中這些物件在取得時都是單例,你可以使用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 Some() {
//...
SingletonRegistry.register(Some.class.getName(), this);
}
}
或者是在建構物件之後主動註冊:
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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
2012-07-15 二叉树
2012-07-15 转:提高VS2010的运行速度
2012-07-15 回溯法求排列问题
2012-07-15 最好使用C++转型操作符
2012-07-15 c++ delete 后还有必要set Null 吗?
2012-07-15 STL array
2012-07-15 转:C++关键字详解(volatile, mutable, explicit, dynamic_ cast<T>(expression))等