Alternative to Singleton Template?

I am trying to create a more flexible Singleton form.

The problems I'm trying to solve are as follows:

  • Singletones cannot be verified easily.
  • They abuse the object-oriented approach, do not allow inheritance , the code becomes linear, and many developers tend to overuse them.
  • They are limited to one instance in the sense of duplicating the same mechanism without duplicating the class itself (for example, the ThreadPool method works as a singleton for each application, but each application has its own instance).

Now the solution I came up with is the following:

  • Make the Singleton class a regular public class with an internal constructor (available only to classes of the same package).
  • As with every product-oriented class, all static properties and static constants have been moved to the SingletonShared inner class, which will be passed as a parameter to the Singleton constructor. Those two are hidden behind the public SingletonFactory , which has a static getInstance(key) method.
  • If we are dealing with a more complex system, where each singleton requires its own unique set of parameters, I added the static method setAdapter(adapter) to SingletonFactory . Using the getShared(key) method, a class that implements ISingletonAdapter should return the SingletonShared value of this instance (for example, SingletonXmlAdapter is passed an Xml file to the constructor and deserializes a specific node based on the key that it gave).

All of the above are packaged as a Singleton package.

Now, for testing purposes, it is possible to mark Singleton as an inner class and implement the ISingleton interface.

Questions:

  • Is this a solution?
  • Is there a better / cleaner / shorter way to achieve the same effect?
  • Which version is best (Singleton as internal or constructor as internal)?

Thanks!

+4
source share
1 answer

I think the solution you describe as SingletonFactory is a ServiceLocator , and your singletones are services.

Is this solution acceptable?

It depends on how and where the Singletons are used. Singletones are not bad on their own if you isolate code that depends on them. Otherwise, you end up injecting a bunch of complex singletones every time you need test fixtures.

If you create an instance of Singletons instead of using static getters / seters, it will be more difficult to add a dependency without using the DI framework unless you pass single games to you, but then you can get a long list of options.

Is there a better / cleaner / shorter way to achieve the same effect?

IoC containers and DI frameworks (subtlety differs) are often used to manage dependencies that would otherwise be Loners. However, even if you eliminate the perversity of Singletons, it’s still good practice to try to isolate areas of dependence on specific services.

+5
source

Source: https://habr.com/ru/post/1382577/


All Articles