How to instantiate a Singleton multiple times?

后端 未结 9 1871
醉酒成梦
醉酒成梦 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条回答
  •  萌比男神i
    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.

提交回复
热议问题