如果我需要一组单例类可搜索/可检索,我应该使用什么设计模式?
我的项目中只需要有一堆类的单个实例。但是,我需要它们是可搜索/可检索的(就像数组一样)。我应该使用什么设计模式?
I need to have only single instances of a bunch of classes in my project. However, I need them to be searchable/retrievable (like an array). What design pattern should I be utilizing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
正如其他人所指出的,您最好重新考虑您的设计并使用依赖项注入。
但是您所描述的类似于 Multiton 模式,因此可能也值得一看。
As others have noted, you might be better off rethinking your design and using dependency injection.
But what you're describing is similar to the Multiton Pattern, so that might also be worth looking at.
Mark 解决方案的 Java 版本:
Java version for Mark's solution:
我不确定我是否理解正确,但我认为也许您需要一个依赖注入容器。查看控制反转/依赖注入模式。
Microsoft Patterns & Practices 提供了一个 DI 容器的实现,称为
Unity。还有其他开源项目,例如 Castle Windsor 等
您可以在容器中注册类型,例如指定您希望某些类型是单例的:
IoC/DI 实际上不止于此,但我希望这个示例有用为您作为起点。
I'm not sure if I understand correctly, but I think that maybe you need a Dependency Injection container. Take a look into Inversion Of Control/Dependency Injection patterns.
Microsoft Patterns &Practices provides an implementation of DI container called
Unity. There are other open source projects like Castle Windsor and others
You can register types in the container, specifying, for example, that you want some types to be singleton:
IoC/DI is actually more than this, but I hope that this example is useful for you as an start point.
将集合封装在单例中。这有效地使所有包含的实例也成为单例。
C# 示例:
您可以通过访问
Singleton.Current.Foos
来枚举和查询 Foos。由于 Singleton 封装了 IFoo 实例,因此它可以确保每个实例只有一个实例,但您也可以将每个 IFoo 实现都设置为 Singleton。然而,这不是必要的。Encapsulate the collection in a Singleton. That effectively makes all the contained instances Singletons as well.
C# example:
You can enumerate and query the Foos by accessing
Singleton.Current.Foos
. Since the Singleton encapsulates the IFoo instances, it can make sure that there's only one instance of each, but you can also make each of the IFoo implementations into Singletons. However, it's not necessary.