静态类与单例 [英] Static classes vs singleton

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

问题描述

当我们可以使用静态类做同样的事情时,为什么我们需要单例?



我研究了很多,但无法理解基本的区别。有人可以用简单的例子用例子解释我。



谢谢

Dinesh



我尝试了什么:



谷歌搜索但无法理解解释

解决方案

使用单例时,可以更容易地控制何时初始化类以使用惰性初始化等等。使用静态类,您几乎可以获得所提供的内容,您的类在创建时初始化。同样使用sigleton你的终极类仍然是一个对象而不是静态类,因此具有随之而来的优点,即它可以更容易地在单元测试中使用,使用继承等OO功能,可以作为对象传递给其他方法,存储状态等。


检查过去的问题答案:

Singleton Class Vs Sealed Class Vs Static Class [ ^ ]

如何判断我应该使用Static类还是singleton类? [ ^ ]

差异静态类和单例模式之间? - 堆栈溢出 [ ^ ]

When we can do the same thing using static classes, why do we need singleton?

I researched a lot but couldn't understand the basic difference. Can somebody explain me in simple words with examples.

Thanks
Dinesh

What I have tried:

google searched but couldnt understand from the explanations

解决方案

Using singletons it is easier to control when the class is initialised to use things like lazy-initialisation etc. Using static classes you're pretty much get what you're given, your class is initialised on creation. Also using sigleton your ultimate class is still an object rather than a static class so has the advantages that come with that, ie it can be used in unit tested easier, use OO features like inheritance, can be passed as an object to other methods, store state etc.


Check past answers to the questions:
Singleton Class Vs Sealed Class Vs Static Class[^]
How can I decide that I should use Static class or singleton class ??[^]
Difference between static class and singleton pattern? - Stack Overflow[^]


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

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