使单例拥有所有静态字段

huangapple go评论59阅读模式
英文:

Making a singleton have all static fields

问题

我一直在想,既然单例允许我们只能有一个对象引用,而我们通过使用静态方法getInstance获得这个引用,那么为什么不能决定将单例中的所有字段都声明为静态的呢?

英文:

I always wondered, since a singleton allows use to have just have one reference to an object, which we get by using the static method getInstance, why can’t we decide to make all fields in a singleton static?

答案1

得分: -1

静态成员是类的一部分,因此会一直保留在内存中,直到应用程序终止,永远不会被垃圾回收。使用过多的静态成员有时预示着您在设计产品时失败了,试图应对静态/过程式编程。这表示面向对象设计受到了损害。这可能导致内存溢出。此外,如果您在Java中将任何方法设为静态,存在某些缺点,例如您无法覆盖任何静态方法,因此这使得测试变得更加困难,您无法用模拟方法替换该方法。由于静态方法维护全局状态,它们可能在并发环境中创建难以检测和修复的微妙错误。

因此,通过使每个方法都是静态的,我们消除了创建单例类的目的,而该目的是节省内存

英文:

> Static members are part of class and thus remain in memory till
> application terminates and can’t be ever garbage collected. Using
> excess of static members sometime predicts that you fail to design
> your product and trying to cop of with static / procedural
> programming. It denotes that object oriented design is compromised.
> This can result in memory over flow. Also there are certain
> disadvantages if you make any method static in Java for example you
> can not override any static method in Java so it makes testing harder
> you can not replace that method with mock. Since static method
> maintains global state they can create subtle bug in concurrent
> environment which is hard to detect and fix.

So by making every method static we eliminate the purpose of making singleton class which is to Saves memory

huangapple
  • 本文由 发表于 2020年4月9日 17:31:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/61118019.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定