英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论