用于全局变量比单例更好的想法

发布于 2025-01-08 08:14:21 字数 149 浏览 2 评论 0原文

我有一个队列应该被某些类使用。

所有类的队列都是相同的,所以我想也许我会将队列作为静态成员放入静态类中。 但我知道这不是很好的OOP。(虽然我认为单例是设计模式之一) 所以我想要一个实现这个队列的想法, 我需要它是唯一的并且可供所有类访问,因为所有类都使用相同的队列。

I have a queue that should be used by some classes.

it is the same queue for all of the classes so I thought maybe I will put the queue in static class as a static member.
But I understand this is not so good OOP.(although I thought that singleton is one of the design pattern)
so I would like an Idea for implement this queue,
I will need it to be unique and accessible to all the classes as all the classes use the same queue.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

〆一缕阳光ご 2025-01-15 08:14:21

你所说的是,你的类共享一些上下文,并且该上下文包含一个队列。我们可以说你的课程取决于这个上下文。

单例模式不是一个好主意的原因是它使用全局(静态)上下文作为公共上下文。 是有限制的,原因有两个:

  1. 清楚地识别类的依赖关系并不容易,因此在不同的环境(例如单元测试环境)下设置它们也不容易。

  2. 完全不可能让该上下文的两个实例并排运行。

因此,一个简单的解决方案是将类的所有依赖项放入上下文类中,然后将所有类与此类的实例链接起来。

另一种更高级的解决方案是使用依赖注入框架。

What you say is that your classes share some context and this context contains one queue. We can say that your classes depend on this context.

The reason for which the singleton pattern is not a good idea is because it uses the global (static) context as the common context. This is limiting for two reasons:

  1. It is not easy to clearly identify the dependencies of your classes, and therefore it is not easy to set them up under different environments (such as a unit testing environment).

  2. It is totally impossible to have two instances of this context run side by side.

So, an easy solution is to put all the dependencies of your classes inside a context class and then link all your classes with an instance of this class.

Another, more advanced, solution is to use a Dependency Injection framework.

瑾夏年华 2025-01-15 08:14:21

我不会将其设为单例,因为这对于程序中的所有类和层都是全局可见的。为需要访问队列的部分提供对队列本身的引用。这样您就可以清楚地确定软件的哪一部分可以访问它。

我在软件项目中经历了非常糟糕的经历,这些项目中有太多单例(又名“XyzManager”),因为它们被从软件的任何部分以疯狂的方式使用。如果可以的话,尽量避免全局变量和单例。最好为您的对象提供他们应该有权访问的内容的引用。

I wouldn't make it a Singleton as this would be globally visible to all classes and layers in your program. Give the parts which need access to the queue the reference to the queue itself. So you clearly determine which part of your software has access to it.

I had very bad experiences with software projects which had too many singletons aka "XyzManager" in it as they were used from any part of the software in a wild way. Try to avoid global variables and Singletons if you can. Better give references into your objects to things they should have access to.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文