What's Alternative to Singleton

Solution 1:

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.

Solution 2:

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.

Solution 3:

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!