Posted by: Cirilo Meggiolaro | 11/1/2008

Unique object instances

This is the first in a series of posts about application design and design patterns. If you have not heard or read about design patterns yet let me give you a brief introduction:

Design patterns are proved and tested solutions for application design problems and provide a very good level of code reuse. There are basically three kinds of design patterns: creational, structural and behavioral patterns.

Let’s take a look at how to design an object and ensure that only a single instance of it will be exposed. For this purpose we are going to use the creational design pattern called Singleton.

Now that you know the problem (to expose a single instance of an object) let’s check the figure below for a while:

Figure 1 – Basic design of a class that implements the singleton design pattern.

 
In the figure 1 we can realize a class called Singleton with one static attribute (uniqueInstance) and two operations (the private constructor and the read-only property that retrieves the single instance).

The Instance property retrieves a valid instance of the Singleton class. The property may use lazy initialization creating the instance only when the first read to the property is requested.

The code snippet below implements the basic code that represents the figure 1.

public class Singleton
{
    private static Singleton uniqueInstance;

    private Singleton()
    {}

    public static Singleton Instance
    {
        get
        {
            if (uniqueInstance == null)
            {
                uniqueInstance = new Singleton();
            }

            return uniqueInstance;
        }
    }
}

Code Optimization

The .NET framework gives us options to use a different approach like sealed class (cannot be inherited) and the instance creation as soon as the Singleton class is referenced.

public sealed class Singleton
{
    private static readonly Singleton uniqueInstance = new Singleton();

    private Singleton()
    {}

    public static Singleton Instance
    {
        get
        {
            return uniqueInstance;
        }
    }
}

You have just read how to apply the Singleton design pattern in .NET. In the next posts, more design patterns.

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

Categories

%d bloggers like this: