How to instantiate a Singleton multiple times?

后端 未结 9 1866
醉酒成梦
醉酒成梦 2020-12-19 04:08

I need a singleton in my code. I implemented it in Java and it works well. The reason I did it, is to ensure that in a mulitple environment, there is only one instance of th

相关标签:
9条回答
  • 2020-12-19 04:37

    you could just make another static method getInstance2 that looks like this:

    class MySingleton
    {
        private MySingleton(){}
        private static MySingleton instance1 = new MySingleton();
        private static MySingleton instance2 = new MySingleton();
    
        public static MySingleton getInstance(){ return instance1; }
        public static MySingleton getInstance2(){ return instance2; }
    }
    
    0 讨论(0)
  • 2020-12-19 04:42

    You can invoke the private constructor of your singleton class using reflection to create a new instance of the class.

    class MySingleton {
        private MySingleton() {
        }
    }
    
    class Test {
        public void test() throws Exception {
            Constructor<MySingleton> constructor = MySingleton.class.getConstructor();
            constructor.setAccessible(true);
            MySingleton otherSingleton = constructor.newInstance();
        }
    }
    
    0 讨论(0)
  • 2020-12-19 04:52

    Traditionally, a Singleton creates its own instance, and it creates it only once. In this case it is not possible to create a second instance.

    If you use Dependency Injection, you can let the framework create the singleton for you. The singleton does not guard against other instances (i.e. it has a public constructor), but the dependency injection framework instantiates only one instance. In this case, you can create more instances for testing, and your object is not cluttered with singleton code.

    0 讨论(0)
  • 2020-12-19 04:55

    A singleton, by definition, can only be instantiated once. However, the fact that your unit test requires two singletons is a strong indication that your object shouldn't really be a singleton, and that you should rethink the singleton design.

    0 讨论(0)
  • 2020-12-19 04:55

    I feel compelled to post this series of articles about how Singletons destroy testability and are poor design choices:

    • Singletons are Pathological Liars
    • Where Have All the Singletons Gone?
    • Root Cause of Singletons

    Short summary: combining logic for what a class does with how it is instantiated makes code that is ugly to test, and should be avoided.

    0 讨论(0)
  • 2020-12-19 04:56

    First, why do you need to create a new singleton to run a unit test? A unit test should not be running concurrently with the normal application, so you should be able to access the original singleton without fear of modifying it..

    Is there a particular reason you need an explicit second singleton?

    0 讨论(0)
提交回复
热议问题