这是Singleton模式的好用吗? [英] Is this a good use of the Singleton pattern?

查看:95
本文介绍了这是Singleton模式的好用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了很多设计自己的____应用程序。

我做的是使单个类保存用户选择的所有自定义。例如:当你选择你想要的东西,它会更新一个单一的getter / setter为绿色。然后当应用程序需要知道选择了什么颜色时,它会从相同的getter / setter获取信息。

我曾经这样做的方式是将信息存储在UI中(只是检查什么颜色是从下拉列表中选择)。

在阅读了关于MVC(我仍然不完全理解MVC)之后,我现在知道这是完全错误的,这就是为什么我把它提炼为包含所有这些的单例类。



现在我想知道这是不是一个坏主意?如果是这样,我该怎么做?



谢谢。

解决方案

我会说这不是真正的Singleton模式的意图。这是一个非常误解的模式,人们最常使用的原因似乎是很容易访问,因为它们通常是静态的。真正发生的是,您有一个配置问题,您正在尝试通过一个静态单例,可以轻松地访问整个应用程序。一个正当的使用是试图控制对真正有限的资源的访问。



如果你认为这只是一个通用的应用程序的配置。有一些可能有更多的意义,但也许只有一个曾经一直在使用。



-Edit-
而不是使用可以使用的Singleton请访问静态考虑使用依赖注入或反转控制。


I make a lot of "design your own ____" applications.
What I do is I make a singleton class to hold all the customizations the user has chosen. For example: When you select you want something green, it updates a getter/setter in the singleton to be green. Then when the application needs to know what color was selected it gets the info from the same getter/setter.
The way I used to do this was by storing the information in the UI (just checking what color was selected from the drop-down).
After reading about MVC (I still dont "fully" understand MVC) I know now that is completely wrong and thats why I abstracted it to the singleton class that holds all that.

Now I am wondering if that is a bad idea too? if so how should I be doing it?

Thanks.

解决方案

I'd say that is not really what the Singleton pattern was intended for. It is a very misunderstood pattern and the most common reason people use it seems to be that it is easy to access since they are often static. What really is happening is that you have a configuration problem that you are trying to get around through a static singleton that can easily be access throughout the application. A 'proper' use would be when trying to control access to a resource that is truly limited.

If you think of it probably really doesnt make sense to have only one universal 'configuration' for an application. It makes a lot more sense to have several but perhaps only one is ever in use at one time.

-Edit- Instead of using a Singleton that can be accessed statically consider using Dependency Injection or Inversion of Control.

这篇关于这是Singleton模式的好用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆