Example of Singleton pattern

The general idea behind a singleton is that it is an object for which it makes no sense to have more than one, and which may need to be accessed all over your program.

The one I end up using all the time is a program configuration.

A typical one of my configuration singletons will contain things like IP addresses, device names, and system limits. When first called, it will typcially read a configuration file (sometimes and/or the system registry on Windows), and load in default values for items not found there. It really makes no sense for a program to have multiple configurations, so all this stuff should just be read in once for the entire program. Additionally, configuration items may need to be accessed by all kinds of different otherwise unrelated classes in the system.


Singleton is a software pattern.

Here is an example in C#.

Having a single queue on a LAN is more of a hardware/network design issue rather than a software concept, so not really applicable. If you were modeling such a thing in software and had to be certain there is only one queue, then it would be applicable.


My personal rule for using singletons is that only get used when it's an error for there to be more than one instance, and global access is required. I would say that a print queue is therefore not a good candidate for singleton: because you don't need global access, and it's also arguable that it's an error to have more than one. In fact, while there may be one "physical" print queue (e.g. on a print server somewhere) that's not what the application cares about, it just needs to submit "jobs":

PrintJobScheduler pjs;
pjs.SubmitPrintJob(myPrintJob);

You don't need my imaginary PrintJobScheduler to be a singleton, even though it may be talking to a "singleton" service somewhere on the network.

Tags:

Singleton