简体   繁体   中英

How do I find where an instance of a Java singleton is created?

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

Singleton通常有一个私有构造函数,因此Singleton类是唯一可以实例化唯一的单例实例的类。

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.

class Singelton
{
    private static Singelton _singelton = null;

    private Singelton()
    {

    }

    // NOT usable for Multithreaded program
    public static Singelton CreateMe()
    {
        if(_singelton == null)
            _singelton = new Singelton();
        return _singelton;        
    }
}

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.

I would use an enum

enum Singleton {
    INSTANCE:
}

or something similar which cannot be instantiated more than once and globally accessible.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM