简体   繁体   English

Singleton类仅具有静态字段和方法,但在内存中具有许多实例

[英]Singleton class only has static fields and methods but has many instances in the memory

In our project, we often use a utility class and its static methods to load some icons. 在我们的项目中,我们经常使用实用程序类及其静态方法来加载一些图标。 This utility class is singleton . 该实用程序类为singleton

But in the running environment, we find 314 instances of this class, under which circumstances does that occur? 但是在运行环境中,我们发现314个此类的实例,在什么情况下会发生?

A static utility class isn't quite the same as a singleton class. 静态实用程序类与单例类不太相同。 (A singleton class is where there is exactly one instance and you access its instance methods, not static methods.) If you don't want instances of your class being created, make sure there is at least one declared constructor and that all constructors are declared private. (在一个单例类中,只有一个实例,您可以访问其实例方法,而不是静态方法。)如果您不希望创建类的实例,请确保至少有一个声明的构造函数,并且所有构造函数都是宣布为私人。 All places where you are creating instances should then light up as compiler errors. 然后,您正在创建实例的所有位置都应作为编译器错误点亮。

当涉及多个类加载器时。

Could you post your implementation? 您可以发布您的实施方案吗? It sounds like you are instantiating the static class multiple times. 听起来您要多次实例化静态类。 Is your constructor private? 您的构造函数是私有的吗? Are you implementing the getInstance method correctly? 您是否正确实现了getInstance方法?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 什么时候单例类优于仅具有静态方法的类? - when is a singleton class preferred over a class that has only static methods? 如果一个类没有状态,那么所有方法都应该是静态的吗? - If a class has no state, should all the methods be static? Mockito 模拟具有无关静态方法的类 - Mockito mock a class that has irrelevant static methods 当一个类只调用另一个有多种方法的类上的一个方法时,如何减少耦合? - How to reduce coupling when one class calls only one method on another class that has many methods? 仅具有静态数据和访问这些数据的方法的类。 如何正确实施? - A class that only has static data and methods to access these data. How to implement that properly? 静态方法和字段是否在定义它们的类的实例中占用内存? - Do Static Methods and Fields take up memory in an instance of the class they are defined in? 普通类,单例类或静态方法以提高性能 - Normal Class, singleton class or static methods for performance 如果它们的类没有成员变量,那么所有方法都应该是静态的 - Should all methods be static if their class has no member variables 单例中类字段和方法的Java顺序 - Java order of class fields and methods in singleton 为什么我们将类声明为抽象类,其中只有具体的方法? - Why we are declaring the class as abstract class it has only concrete methods in it?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM