如何确定应该使用静态类还是单例类? [英] How can I decide that I should use Static class or singleton class ??

查看:74
本文介绍了如何确定应该使用静态类还是单例类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



如何确定应该使用静态类还是单例类?

谢谢,

解决方案

单例模式是对象创建控制模式.它允许您控制对象的实例化(在这种情况下,将其限制为仅一个实例).

另一方面,静态类根本无法实例化.

尝试考虑您要构建的抽象模型.如果您的班级代表有形的事物(应该只存在其中之一),则您应该使用单例.如果您只是在编写一些辅助方法,则应将其设置为静态.

考虑到单例模式允许将来更改创建控制算法以允许管理数量的多个实例,这也很生气.

考虑到所有这些,还值得注意的是,在许多情况下,单例类实际上并没有带来很多好处,但会增加复杂性,并可能导致类的紧密耦合.它们本质上构成了一个可以从任何地方访问的全局变量.除非您的班级确实确实代表了一些有限的全局系统资源,否则也许值得考虑使用某种创建并传递"或IOC/依赖注入模式来管理您的班级创建.

1. Singleton提供了对类实例的引用/指针.然后,您可以将此引用作为其他函数的参数传递.

2.您不能扩展静态类,但可以扩展单例,因为静态类是隐式密封的.

3.使用Singleton,您可以控制可以同时使用它的用户数量.


静态是从语言角度来看的一个概念.静态意味着您不创建对象.

但是Singleton是一个概念,它使您只能创建一个实例变量.

这取决于您的要求.如果您能告诉我您的要求是什么,最好给您答案.


Hi,

How can I decide that I should use Static class or singleton class ??

Thanks,

解决方案

The singleton pattern is a object creation control pattern. It allows you to control the instantiation of your object (in this case by restricting it to just one instance).

On the other hand, static classes are not instantiable at all.

Try and think about what abstraction model you are trying to build. If your class represents something tangible, (only one of which should ever exist) you should probably use a singleton. If you are just writing some helper methods you should probably make them static.

It''s also wroth considering that the singleton pattern allows for future alteration of the creation control algorithm to allow a managed number of multiple instances.

All this considered, it''s also worth noting that in many cases singleton classes don''t actually bring a huge amount of benefit but add complexity and can cause tight coupling of your classes. They essentially form a global variable accessible from everywhere. Unless your class really does represent some restricted global system resource, perhaps it''s worth considering some kind ''create and pass down'' or an IOC/dependency injection pattern to manage your class creation instead.


1. Singleton gives a reference/pointer to the class instance. You can then pass this reference as a parameter for some other function.

2. You can''t extend static classes, but singletons you can, Since static classes are implicitly sealed.

3. with Singleton you can control the amount of users that can use it at the same time.


Static is a concept from the language point of view. Static means you dont create an object.

But Singleton is a concept which lets you create only one instance variable.

It depends on your requirement. If you can tell me what is your requirement, it would be better to give you answer.


这篇关于如何确定应该使用静态类还是单例类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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