最常见的滥用单身人士的例子 [英] Most common examples of misuse of singleton class

查看:74
本文介绍了最常见的滥用单身人士的例子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你应该什么时候不要使用单身班,虽然这可能非常诱人?如果我们列出了我们应该注意避免的单身性的最常见例子的列表。

解决方案

不要使用单例来进行可扩展的资源。



这可能听起来很愚蠢,但是如果你宣布一个单例,那么你做的很强说明它是绝对独一无二的。你正在围绕它构建代码,越来越多。而当你发现数千行代码之后,它根本不是一个单一的代码,所以你在你面前有大量的工作,因为所有的其他对象都希望WizBang这个神圣的对象成为一个单身人士



典型示例:这个应用程序只有一个数据库连接,因此它是单例。 - 馊主意。您可能希望将来有多个连接。更好地创建一个数据库连接池,并只用一个实例来填充它。使用像一个Singleton,但所有其他代码将具有访问池的可扩展代码。



编辑:我理解,理论上你可以扩展单身成几个对象。然而,没有真正的生命周期(如汇集/解压缩),这意味着没有对已经发布的对象的真正所有权,即现在的多单例必须是无状态的,以被不同的方法和线程同时使用。 / p>

When should you NOT use a singleton class although it might be very tempting to do so? It would be very nice if we had a list of most common instances of 'singletonitis' that we should take care to avoid.

解决方案

Do not use a singleton for something that might evolve into a multipliable resource.

This probably sounds silly, but if you declare something a singleton you're making a very strong statement that it is absolutely unique. You're building code around it, more and more. And when you then find out after thousands of lines of code that it is not a singleton at all, you have a huge amount of work in front of you because all the other objects expect "the" sacred object of class WizBang to be a singleton.

Typical example: "There is only one database connection this application has, thus it is a singleton." - Bad idea. You may want to have several connections in the future. Better create a pool of database connections and populate it with just one instance. Acts like a Singleton, but all other code will have growable code for accessing the pool.

EDIT: I understand that theoretically you can extend a singleton into several objects. Yet there is no real life cycle (like pooling/unpooling) which means there is no real ownership of objects that have been handed out, i.e. the now multi-singleton would have to be stateless to be used simultaneously by different methods and threads.

这篇关于最常见的滥用单身人士的例子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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