Singleton class for an object with parameters

I realized that I should have only one instance of an object called StdSchedulerFactory , launched at a time. So far I have created an object like this

 StdSchedulerFactory sf = new StdSchedulerFactory(properties); 

And the properties is NameValueCollection . How can I write a Singleton class for this object so that the sf variable always has one instance in the whole program?

+7
c # design-patterns singleton
source share
3 answers

Part of the Singleton template is usually a private constructor, so other classes cannot create new instances.

A workaround for parameters coming from outside the class is to add the "Init" or "Configure" function:

 public static void Configure(NameValueCollection properties) { } 

Of course, if you forget to call this function, you can get behavior that you do not want; therefore, you can set the "Configured" flag or something similar so that your other functions can react accordingly if that function has not yet been called.

+9
source share

Here is the basic implementation of Singleton. It is not thread safe.

 public sealed class StdSchedulerFactory { private static readonly StdSchedulerFactory instance; private NameValueCollection _properties; private StdSchedulerFactory(NameValueCollection properties) { _properties = properties; } public static StdSchedulerFactory GetInstance(NameValueCollection properties) { if (instance == null) { instance = new StdSchedulerFactory(properties); } else { return instance; } } } 
+1
source share

These are my two favorite ways to implement a simple singleton pattern. The second option is easier when debugging :)

 public sealed class SingletonOne { private static readonly Lazy<SingletonOne> instance = new Lazy<SingletonOne>(() => new SingletonOne()); private Lazy<Controller> controller = new Lazy<Controller>(() => new Controller(properties)); private static object properties = null; public static SingletonOne Instance { get { return instance.Value; } } public Controller GetController(object properties) { SingletonOne.properties = properties; return this.controller.Value; } } public sealed class SingletonTwo { private static readonly SingletonTwo instance = new SingletonTwo(); private Controller controller; private static object properties = null; public static SingletonTwo Instance { get { return SingletonTwo.instance; } } public Controller GetController(object properties) { SingletonTwo.properties = properties; if(this.controller == null) { this.controller = new Controller(SingletonTwo.properties); } return this.controller; } } public class Controller { public Controller(object properties) { } } 
+1
source share

All Articles