Click here to Skip to main content
16,015,755 members
Articles / Programming Languages / C#
Article

My Personal and Also Another Approach to Handling the Singleton Design Pattern

Rate me:
Please Sign up or sign in to vote.
1.95/5 (8 votes)
14 Sep 20071 min read 27.2K   70   19   7
Quick and simple use of the singleton design pattern

Introduction

I wanted to have my own and simple handling for the singleton design pattern without implementing it many times. Singleton is an object-based creation pattern. You should implement it to ensure that only one instance of a class exists to have a global access point.

I often used the singleton design pattern to hold the settings of a configuration file. However, I had to implement the pattern every time and sometimes I had to write a method for initializing some variables of the instance, as well as implement a check to watch for instance initialization. I needed a quick and simple way to use the singleton design pattern... And here comes my approach to solving this.

Using the Code

I delegated creation and initialization of the singleton class instance to a generic builder class called UZi.Singleton.SingletonBuilder<T>. See more details in my source code. You can (and should) check the arguments for the constructor of your singleton class with the delegate UZi.Singleton.SingletonClassConstructorArgsChecker. Now you can write code like this, if x is a defined class:

C#
x singletonInstanceOfX = UZi.Singleton.Singleton<x>, 
    UZi.Singleton.SingletonBuilder<x>.GetInstance(
    UZi.Singleton.SingletonClassConstructorArgsChecker
    )someMethodToCheckArgsForTheSingletonClassCtor, 
    new object[] { 1, "string_value" });

You can now use singletonInstanceOfX everywhere in your application and you only ever have this one instance of x. Don't forget to make the constructor of your class, which should be a singleton class, private or protected!

Points of Interest

With my approach, you can simply use the singleton design pattern. You'll never have to implement it for a class serving as a singleton instance. We also never have to implement a builder class to build an initialized instance of our singleton class. Use the generic code and save time.

History

  • 2007-09-12: First version
  • 2007-09-12: Tried to fix some formatting mistakes

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
Germany Germany
.NET Professional: 'specialist for application development' (a german job title)

I normally develop applications in C# with the .net-framework 2.0+/3.0 and currently databases for MS Sql Server 2005 and MS Access 2003+.

I'm an employee of an office which is working for insurances and which is watching investigations of damages for incorrect items, plausibility and so on and my job is to develop software to automate these processes. I developed for example an application which can extract values from ocr-texts using regular expressions and save these values into a database for later calculations or other processes.

Comments and Discussions

 
GeneralFurther reading Pin
Peter Ritchie17-Sep-07 9:59
Peter Ritchie17-Sep-07 9:59 
GeneralThanks for your contribution Pin
jonnii12-Sep-07 6:31
jonnii12-Sep-07 6:31 
AnswerRe: Thanks for your contribution Pin
SaxoniaCoder12-Sep-07 18:47
SaxoniaCoder12-Sep-07 18:47 
GeneralRe: Thanks for your contribution Pin
jonnii12-Sep-07 22:48
jonnii12-Sep-07 22:48 
GeneralRe: Thanks for your contribution Pin
Peter Ritchie17-Sep-07 9:53
Peter Ritchie17-Sep-07 9:53 
GeneralRe: Thanks for your contribution Pin
Phil_N12-Sep-07 23:03
Phil_N12-Sep-07 23:03 
"i think there is no other way if you need only one instance of a class".

Setting aside for a moment whether there really is only one way, the question here is: Why do you *need* to enforce only a single instance of the class?

The clue as to the usual reason was given in your article, "to have a global access point". Which leads to the next question, "Why do you want to have a global access point". Again you answer this question (hey, you're doing well so far): As a substitute for, "The use of global variables".

Ok, that's a noble goal - but is a singleton the only, or even best, way to avoid global variables?
In fact, I would say that using singletons in this way is basically the same as using global variables. Ok, so you get a name scope, so you cut down pollution of the global namespace (esp. in C++) - but you could use namespaces for that!
Ok - you get to delay initialisation until the point of first use - which may or may not be an advantage - but certainly brings with it all the problems of when are the objects *destroyed* (read Alexandrescu's excellent discussion of a generic singleton implementation in C++ for more on that - and btw he's an example of one of the most brilliant minds in the industry struggling to make singletons work - he's since given up).

In addition to the objections that jonnii enumerates (and don't underestimate the testability) the use of singletons tends to make your designs entangled messes with no cohesion. Furthermore they are infectious - introduce one and more tend to come along, poisioning your code base.

But what are the alternatives?
Well, the main alternative is extremely simple - so simple in fact that most people overlook it. Certainly simpler than trying to get a singleton right!
It's known by various names, or no name at all, but in the circles I frequent it's known as, "Parameterise From Above".
Simply put - you create and initialise the objects you need to work with in one place, perhaps in main (or whatever the entry point is in your language of choice), and pass them down to all objects that need them. You can wrap them up in context objects, or whatever makes sense, to minimise passing lots of objects around - but you get to control every point of the the lifecycle, number of instances, and who gets which version etc.
It suffers from none of the problems of singletons or globals, gives no surprises to maintainers, who will all be familiar with the idea of passing objects around, and is easy to get right. I've used this pattern in C, C++, C#, Java and others - and it works pretty much the same way in all.

I admit that, until a couple of years ago, I was holding out on logging objects as being a special case that justified the use of singletons.
I was wrong.
I started PfAing my log objects and suddenly everything fell into place! So easy to have different flavours of logging, or null log objects - and everything could be nicely interface based. I saw none of the downsides I had expected (extra overhead passing around lots of little objects).

I urge you (and I include any readers here, not just the author) to reconsider singleton - google around the web for more examples of it's status as an anti-pattern - play with the alternative(s) and see for yourself. You won't regret it!


[)o
IhIL..

GeneralRe: Thanks for your contribution Pin
Urs Enzler17-Sep-07 22:39
Urs Enzler17-Sep-07 22:39 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.