“Ensure a class only has one instance, and provide a global point of access to it.”

Design Patterns: Elements of Reusable Object-Oriented Software

The Singleton pattern is something really simple. Let’s assume you have a class, which represents your data access layer, as a whole. As you might guess, a DAL object can grow quite large, especially when it stores disconnected data, such as in the case of a DataSet. There might be good reasons to have multiple ones instantiated of them, but maybe that’s not the best idea ever.

This is when Singleton pattern comes to place. It ensures that only one and only instance can live of a specific class, and that instance is accessible for every part of your code which needs it for its work. Implementing this behavior in code is very easy, consider the following example:

public sealed class MySingleton
                public static readonly MySingleton SoleInstance = new MySingleton();
                //rest of the class

As you can see, providing a static readonly method which returns an instance of the MySingleton class serves the purpose. We made sure that another instance of the class cannot be created however hard we try. We also marked the class as sealed, thereby eliminating the possibility of subclassing it. However, it isn’t a requirement, in some cases, you’d need to use a subclass of your singleton class to fulfill an advanced requirement.

Further Readings:

Singleton Pattern on Wikipedia

Design Patterns (book) pp 127-134


Tags: ,

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: