What's Alternative to Singleton

John Mill picture John Mill · Aug 19, 2009 · Viewed 37.9k times · Source

We have a class that holds configuration information for the application. It used to be a singleton. After some architectural review, we were told to remove the singleton. We did see some benefits of not using singleton in the unit testing because we can test different configurations all at once.

Without singleton, we have to pass the instance around everywhere in our code. It's getting so messy so we wrote a singleton wrapper. Now we are porting the same code to PHP and .NET, I am wondering if there is a better pattern we can use for the configuration object.

Answer

FrankS picture FrankS · Aug 19, 2009

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

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.