views:

984

answers:

2

The link over here lists ([http://www.yoda.arachsys.com/csharp/singleton.html][1]) some singleton patterns in C#. The article also describes the obvious that a singleton is not meant to accept parameters which “as otherwise a second request for an instance but with a different parameter could be problematic”. This means that any parameters you need to get the class working should be induced as a property.

I am curious to know if there are any parameterized singleton design patterns out there. Accepting values as a property does not enforce anything to the consumer.

+2  A: 

Based on your question, it seems you may be looking at an Abstract Factory pattern (creates an instance of several families of classes) that keeps an internal list/dictionary of classes that have already been instantiated, thus mimicking the singleton pattern functionality.

You would then use this factory class to request an object based on parameters you've passed in, and if it exists in its internal list it gets returned, and if not, a new instance is created and then added to the list and returned.

Darksider
+1  A: 

his means that any parameters you need to get the class working should be induced as a property.

Ideally singleton class should not depend on external code.

In case when you need to provide additional information to singleton constructor, you can just create a pool of objects.

It can be a simple list or any other suitable data structure. You will need to make it thread-safe (if it matters) and guarantee that there will not be multiple objects instantiated with the same parameters.

Basically you will have a class factory. It will return the same object for the same parameters.

In this case you will have N singleton objects - i.e. objects with different state will be treated as completely different instances.

You can find examples of such singletons in Inversion of Controls containers.

For example you can have some service that depends on other services. When you call container.Get(type of service). DI container will automatically initialize service instance with required parameters and return it to caller. But this service instance becomes singleton - you will not be able to create another service with the same parameters.

aku