Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's Alternative to Singleton

People also ask

Which of the following is an alternative for a singleton in Java?

Using dependency injection to avoid singletons.

What's wrong with singleton pattern?

Singletons hinder unit testing: A Singleton might cause issues for writing testable code if the object and the methods associated with it are so tightly coupled that it becomes impossible to test without writing a fully-functional class dedicated to the Singleton.

How can we avoid singleton?

Serialization is used to convert an object of byte stream and save in a file or send over a network. Suppose you serialize an object of a singleton class. Then if you de-serialize that object it will create a new instance and hence break the singleton pattern.


The Google Testing blog has a series of entries about avoiding Singleton (in order to create testable code). Maybe this can help you:

  • Using dependency injection to avoid singletons
  • Singletons are Pathological Liars
  • Root Cause of Singletons
  • Where have all the Singletons Gone?

The last article explains in detail how to move the creation of new objects into a factory, so you can avoid using singletons. Worth reading for sure.

In short we move all of the new operators to a factory. We group all of the objects of similar lifetime into a single factory.


The best way is to use a Factory pattern instead. When you construct a new instance of your class (in the factory) you can insert the 'global' data into the newly constructed object, either as a reference to a single instance (which you store in the factory class) or by copying the relevant data into the new object.

All your objects will then contain the data that used to live in the singleton. I don't think there's much of a difference overall, but it can make your code easier to read.


I might be stating the obvious here, but is there a reason why you can't use a dependency-injection framework such as Spring or Guice? (I believe Spring also is available for .NET as well now).

That way, the framework can hold a single copy of the configuration objects, and your beans (services, DAOs, whatever) don't have to worry about looking it up.

This is the approach I usually take!


If you use Spring Framework, you can just create a regular bean. By default (or if you explicitly set scope="singleton") only one instance of the bean is created and that instance is returned every time the bean is used in a dependency or retrieved via getBean().

You get the advantage of the single instance, without the coupling of the Singleton pattern.


The alternative is passing in what you need instead of asking an object for things.