Singleton Pattern with non-default constructor

T

Tom

In a web-application I need to read some configuration from a database.
I like to write a configuration class which will be implemented as
thread-safe singleton.

I connect through ODBC to the database. So to be able to do that I need
to pass the Datasource Name.

How can I create a singleton that has a constructor with a parameter?
Standard singleton pattern always use the default constructor. To
provide an init(string datasource_name) method is no real fun, since the
state of the singleton instance needed to be checked whenever used.

Is there any better solution to this?

Tom
 
A

Arne Vajhøj

Tom said:
In a web-application I need to read some configuration from a database.
I like to write a configuration class which will be implemented as
thread-safe singleton.

I connect through ODBC to the database. So to be able to do that I need
to pass the Datasource Name.

How can I create a singleton that has a constructor with a parameter?
Standard singleton pattern always use the default constructor. To
provide an init(string datasource_name) method is no real fun, since the
state of the singleton instance needed to be checked whenever used.

Is there any better solution to this?

From the philosophical point of view you could arhue that if the
parameter is not fixed, then it is not really a singleton.

From the practical point of view you would probably just have the
constructor read the name from a config file.

The alternative would be a multipleton, where the GetInstance
method has a string argument and the static instance field
is a Dictionary<string,X> and the GetInstance lookup and create
if necessary.

Arne
 
B

Bob Powell [MVP]

If the object returned is state-dependent on the constructor parameter then
this is not a good target for the singleton pattern.

Effectively, the singleton objects state will change for all objects that
have a reference to it.

In this case, and if you really want to use a singleton, a more correct
method would be to maintain the pattern as described by the pattern and
provide a method to set the state.

--
--
Bob Powell [MVP]
Visual C#, System.Drawing

Ramuseco Limited .NET consulting
http://www.ramuseco.com

Find great Windows Forms articles in Windows Forms Tips and Tricks
http://www.bobpowell.net/tipstricks.htm

Answer those GDI+ questions with the GDI+ FAQ
http://www.bobpowell.net/faqmain.htm

All new articles provide code in C# and VB.NET.
Subscribe to the RSS feeds provided and never miss a new article.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top