Recent Weblogs

Links I like

The Simplest Singleton

A singleton is a class that only allows one instantiation of itself in all environments that it is available.

My approach to this idea was to leverage a few crucial techniques to achieve this pattern. First to note would be the two static variables of the class which will govern logic flow. Instance and Flag, instance is the reference to the one instantiation, and flag is a boolean which will determine whether the constructor throws an error or allows instantiation.

The Impenetrable Constructor

The constructor uses a condition using the private static variable flag to determine whether it will throw an error. This enforces the fact that only by controlling this private variable can you allow an instantiation.

The Gateway - getInstance

The method to retrieve the instance is getInstance, this method uses a simple condition, if the instance is already created, then simply return that immediately. If its not been set, then set the flag to true, create the instance, set the flag to false, return the instance.

An Evasive Abstract

My initial hopes were to create an abstract or base class for this singleton pattern, allowing subclasses to only override basic functions that wouldn't affect logic flow so this pattern could be easily inherited. Unfortunately for my purposes, static methods/properties aren't inherited by subclasses. So I thought perhaps an interface would be beneficial, as many classes need to inherit from some other class but need special functionality like this, but static methods/properties again aren't enforced in any way through an interface.

Syntax and an Example

I've posted some syntax on a very bare bones implementation of my singleton approach. I made it a dynamic class so that it was easy to test that the single reference was preserved regardless of where the code was being used.





Resources

Comments are Disabled.