Sunday, October 03, 2004

How to use the singleton design pattern..

Since my ColdFusion days, I've had a interest in software design patterns (I admit that my understanding of design patterns is really at the conceptual, not practical level -- that's changing though...).

I used my first pratical application of a bona-fide software design pattern today however: The Singleton. From what I gather, it's likely to simplest to understand and implement -- so... uh, it's nothing fancy.

The Singleton design pattern is used to ensure that only one instance, a "single instance" is ever instantiated during the life of an application. It can (and from what I understand, should) be used in place of a class composed entirely of static methods. The Singleton ensures that a single instance of the class is instantiated the first time a method in that class is requested, and then the same instance is accessed many times during the life of the application.

Implementaion of the Singleton requires applying three basic concepts:
  1. a protected constructor;
  2. a private static variable of the class type;
  3. and a public static method (typically named "instance") that controls the instantiation of new classes

Here's how it works:

  1. To instantiate a new class, the application calls the instance method rather than the typical "new class()" syntax.
  2. The intance method checks the private variable for null (meaning the class hasn't already been instantiated).
  3. If the protected variable is null, then the intance method calls the protected constructor which instatiates the class and returns the instance;
  4. if the protected variable is not null (ie: an instance already exists), then the instance method simply returns the already instantiated class.

Voila! Only one instance of a Singleton class can ever exists. It's really quite simple and elegant -- which I guess is what makes it really cool.


No comments: