为什么在静态字段和方法上使用单例? [英] Why use singleton over static fields and methods ?

查看:60
本文介绍了为什么在静态字段和方法上使用单例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尽管我们可以通过静态字段和方法获得单例的行为,但为什么要使用单例呢?

预先感谢,
Raz

Although we can get singleton liek behaviour with static fields and methods, then why do we use singletion ?

Thanks in advance,
Raz

推荐答案

答案的一半在您的问题之内.

1)将字段声明为静态时会发生什么?
答案-您的字段在所有实例中变为公用/共享.

2)将方法声明为静态时会发生什么?
答案-您的方法在所有实例中变得通用/共享.简而言之,您不需要创建类的单独实例即可访问此静态方法.

3)为什么选择Singleton?
答案-因为现在我们正在从方法到类上一层.如果要确定,它们应始终是应用程序中使用的Class的一个实例,则需要Singleton.

例如-一个处理您的应用程序MasterData的类.您不需要此类的多个实例,因为您在这里处理MasterData,因此 Singleton模式是适用的.

请查看下面的链接以获取有关Singleton Pattern的更多详细信息.

http://www.dofactory.com/Patterns/PatternSingleton.aspx [
Half of the answer is within your Question.

1) What Happens when you declare a field as a static?
Answer - Your Field becomes common/shared for all the instances.

2) What Happens when you declare a Method as a static?
Answer - Your Method becomes common/shared for all the instances. In short you does not require to create separate Instance of a Class to access this static Method.

3) Why Singleton?
Answer - Because now we are going one level up from Method to Class. If you want to make sure, their should be always one instance of your Class used in application then Singleton is required.

For Example - A Class which is dealing with MasterData of your application. You does not require multiple instances of this Class because you are dealing with MasterData here, hence Singleton Pattern is applicable.

Please have look at below link for more details on Singleton Pattern.

http://www.dofactory.com/Patterns/PatternSingleton.aspx[^]


"Singleton与静态"已经过时论点,如果您只是用Google搜索,就会在网上找到很多讨论.
基本上,它们做的事情非常相似,但有三个重要区别.

1)静态类在程序启动时实例化.单例在首次使用时创建.
2)静态类是sealed-您不能从它们派生.
3)单例更容易使线程安全.

但是,通常,对于初学者,我建议使用static;对于更高级的编码人员,我建议使用singleton-主要是因为static更易于解释和理解,并且singleton更容易出错!
"Singleton vs static" is an old argument, and you will find lots of discussions on the net if you just google for that.
Basically, they do very similar things, but with three important differences.

1) Static classes are instantiated when the program starts. Singletons are created when they are first used.
2) Static classes are sealed - you cannot derive from them.
3) Singletons are more easily made thread safe.

But, generally, for beginners I recommend static and for more advanced coders, I recommend singleton - mostly because static is easier to explain and understand, and singleton is a lot easier to get completely wrong!


这篇关于为什么在静态字段和方法上使用单例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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