编程中单例的目的 [英] Purpose of singletons in programming

查看:71
本文介绍了编程中单例的目的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个相当宽松的问题.我目前对单例的理解是,它们是您以仅创建一个实例的方式设置的类.

This is admittedly a rather loose question. My current understanding of singletons is that they are a class that you set up in such a way that only one instance is ever created.

在我看来,这听起来像是一个静态类.主要区别在于,对于静态类,您不能/不能实例化它,而只是使用它,例如Math.pi().使用单例课程,您仍然需要做类似的事情

This sounds a lot like a static class to me. The main difference being that with a static class you don't / can't instance it, you just use it such as Math.pi(). With a singleton class, you would still need to do something like

singleton firstSingleton = new singleton();
firstSingleton.set_name("foo");

singleton secondSingleton = new singleton();

如果我错了,请纠正我,但是现在firstSingleton == secondSingleton,是吗?

Correct me if i am wrong, but firstSingleton == secondSingleton right now, yes?

secondSingleston.set_name("bar");
firstSingleton.report_name(); // will output "bar" won't it?

请注意,我正在独立询问这种语言,更多地是关于这个概念.因此,我实际上并不担心如何编写这样的类,而是担心您为什么不想这样做以及需要考虑什么.

Please note, I am asking this language independently, more about the concept. So I am not worried about actually how to code such a class, but more why you would wan't to and what thing you would need to consider.

推荐答案

相对于由静态组成的类,单例的主要优点是您以后可以轻松地确定实际上需要多个实例,例如每个线程一个.

The main advantage of a singleton over a class consisting of statics is that you can later easily decide that you need in fact more than one instance, e.g. one per thread.

但是,在实践中,单例的主要目的是使人们对拥有全局变量感到不那么沮丧.

However, in practice the main purpose of singletons is to make people feel less bad about having global variables.

使用单例的实际示例:您有一个使用SQL数据库的应用程序,并且需要一个连接池.这样的池的目的是重用数据库连接,因此您绝对希望所有客户端都使用相同的池.因此,将其作为单例是正确的设计.但是有一天,您需要该应用程序连接到第二数据库服务器,并意识到您无法与同一池中的其他服务器建立连接.因此,您的整体一个实例"单例变成每个数据库服务器一个实例".

A practical example for a good use of a singleton: you have an app that uses an SQL database and you need a connection pool. The purpose of such a pool is to reuse DB connection, so you definitely want all clients to use the same pool. Thus, having it as a singleton is the correct design. But one day you need the app to connect to a second DB server, and realize that you cannot have connections to different servers in the same pool. Thus your "one instance overall" singleton becomes "one instance per DB server".

这篇关于编程中单例的目的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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