Moshe Bixenshpaner
Moshe Bixenshpaner

Reputation: 1948

An alternative to the Singleton pattern?

I'm trying to design a more flexible form of Singleton.

The problems I'm trying to address are the following:

Now, the solution I came up with so far is the following:

All of the above are packed as a Singleton package.

Now, for test-ability purposes, there is an option of marking Singleton as an internal class and have it implement an ISingleton public interface.

Questions:

  1. Is this solution acceptable?
  2. Is there a better / cleaner / shorter way of achieving the same effect?
  3. Which version is best (Singleton as internal vs. constructor as internal)?

Thanks!

Upvotes: 4

Views: 750

Answers (1)

Garrett Hall
Garrett Hall

Reputation: 30022

I think the solution you are describing as the SingletonFactoryis the ServiceLocator pattern and your Singletons are services.

Is this solution acceptable?

It depends on how and where you use the Singletons. Singletons are not bad in themselves, so long as you isolate the code that depends on them. Otherwise you end up injecting a bunch of complex Singletons every time you need a test fixture.

If you instantiate Singletons rather than using static getters/setters it will be more difficult to dependency inject without using a DI framework, unless you pass you singletons in, but then you can end up with a long list of parameters.

Is there a better / cleaner / shorter way of achieving the same effect?

IoC containers and DI frameworks (subtlety different) are often used to control dependencies that would otherwise be Singletons. However even if you eliminate the evils of Singletons, it is still good practice to try to isolate areas of dependency on particular services.

Upvotes: 5

Related Questions