如何找到 Java 单例实例的创建位置?
在一个大型、复杂的程序中,要发现其中的位置可能并不容易 代码中一个Singleton已经被实例化了。跟踪创建的单例实例以便重用它们的最佳方法是什么?
问候, RR
In a large, complex program it may not be simple to discover where in the
code a Singleton has been instantiated. What is the best approach to keep track of created singleton instances in order to re-use them?
Regards,
RR
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Singleton 通常有一个私有构造函数,因此 Singleton 类是唯一可以实例化该构造函数的类并且只有单例实例。
A Singleton usually has a private constructor, thus the Singleton class is the only class which can instantiate the one and only singleton instance.
单例类
开发人员有责任确保实例在多个调用中被重用。作为用户,您不应该担心它。
现在,您可以从代码中的任何位置实例化
Singelton
,您可以实例化多少次,并且每次将其分配给不同的引用。但 c'tor 只被调用一次。It's the responsibilty of
singleton class
developer to make sure that the instance is being reused on multiple calls.As a user, you shouldn't worry about it.
Now, from anywhere in your code, you can instantiate
Singelton
, how many times you like and each time assign it to different reference. but c'tor is called ONLY once.我会使用
enum
或类似的东西,它不能多次实例化并且可以全局访问。
I would use an
enum
or something similar which cannot be instantiated more than once and globally accessible.
创建/返回单例的命名方法的一般做法是
getInstance()
。我不明白当你在代码中找不到创建单例的地方时的情况,但你可以搜索这个方法名称。如果您想捕捉单例创建的确切时刻 - 您可以使用 AOP。 AspectJ 是 java 中的一个很好的例子。您将能够在创建类或调用 getInstance() 方法之前/之后执行代码。
如果您的问题是关于重用创建的单例,请搜索此站点。 例如
General practice for naming methods which create/return singletons is
getInstance()
. I don't understand the situation when you can't find the place in code where singletons created, but you can search for this method name.If you want to catch the exact moment of singleton creation - you can use AOP. AspectJ is a good example in java. You will be able to execute your code before/after creation of class or calling
getInstance()
method.If your question is about reusing of created Singletons, then search this site. For example