可观察类可以构造为单例吗?

发布于 2024-11-03 10:37:59 字数 88 浏览 2 评论 0原文

我正在使用观察者模式(在 Java API 的帮助下)用 Java 编写一个程序。如果某些可观察量有多个实例,则程序可能会崩溃。我应该将它们实现为单例吗?推荐吗?

I'm making a program in Java with the Observer pattern (with the help of the Java API). If some of the observables had more than one instance, the program could crash. Should I implement them as singleton? Is it recommended?

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

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

发布评论

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

评论(3

千紇 2024-11-10 10:37:59

我应该将它们实现为单例吗?推荐吗?

当然你可以这样做。是否是个好主意取决于实际情况。

  • 这些东西在概念上是单例的,还是只是试图让错误消失的一种黑客行为? (或者换句话说,真正的问题是你的应用程序设计错误......)

  • 单例在单元测试方面确实存在问题。这不是一个阻碍,但它是人们倾向于避免它们的原因之一。

Should I implement them as singleton? Is it recommended?

Of course you can do this. Whether it is a good idea depends on the actual context.

  • Are these things conceptually singleton, or is this just a hack to try to make bugs disappear? (Or to put it another way, is the real problem that your application design is wrong ...)

  • Singletons do have issues with respect to unit testing. This is not a show stopper, but it is one of the reasons that people tend to avoid them.

情话墙 2024-11-10 10:37:59

是的,GoF 将单例列为观察者的相关模式(以及中介者):

ChangeManager 可以使用单例模式来使其唯一且可全局访问。

ChangeManager 是示例代码中他们的 Observable。

我使用了 Singleton Observable (此处)每次持久性单元发生相关更改时更新 GUI。该程序不会崩溃,但如果有更多实例,它将无法按预期运行。

Yes, the GoF lists the Singleton as a related pattern (along with the Mediator) to the Observer:

The ChangeManager may use the Singleton pattern to make it unique and globally accessible.

ChangeManager is their Observable in the sample code.

I have used a Singleton Observable (here) to update the GUI everytime relevant changes occur to the Persistence Unit. The program won't crash but it won't function as expected if there were more instances.

能怎样 2024-11-10 10:37:59

我之前做过并且没有任何问题,正是因为我使用了单例。
该模式就在那里使用它。

I did it before and didn't have any problems exactly because I used a singleton.
The pattern is there to use it.

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