Thursday 22 September 2011

C# - Singleton Pattern vs. Static Classes

Problem: Store some common data in a singleton or static class about your program in an object array, which you store in a class. It saves state between usages and stores some caches, and must be initialized only once and shared in many code locations. Making a new object each time would be expensive.

Solution

This article covers the differences between the singleton design pattern and the static keyword on C# classes. Static classes and singletons both provide sharing of redundant objects in memory, but they are very different in usage and implementation.

Introducing the Singleton Pattern

Our ideal solution is called the singleton design pattern. Here is an implementation of a singleton that I will use. As you know, a singleton is a single-instance object. It is highly efficient and very graceful. Singletons have a static property that you must access to get the object reference.
/// <summary>
/// Sample singleton object.
/// </summary>
public sealed class SiteStructure
{
    /// <summary>
    /// Possible an expensive resource we need to only store in one place.
    /// </summary>
    object[] _data = new object[10];

    /// <summary>
    /// Allocate ourselves. We have a private constructor, so no one else can.
    /// </summary>
    static readonly SiteStructure _instance = new SiteStructure();

    /// <summary>
    /// Access SiteStructure.Instance to get the singleton object.
    /// Then call methods on that instance.
    /// </summary>
    public static SiteStructure Instance
    {
        get { return _instance; }
    }

    /// <summary>
    /// This is a private constructor, meaning no outsides have access.
    /// </summary>
    private SiteStructure()
    {
        // Initialize members, etc. here.
    }
}
 

Static Class Example

In the following example, look carefully at how the static keyword is used on the class and constructor. Static classes may be simpler, but the singleton example has many important advantages, which I will elaborate on after this code block.
/// <summary>
/// Static class example. Pay heed to the static keywords.
/// </summary>
static public class SiteStatic
{
    /// <summary>
    /// The data must be a static member in this example.
    /// </summary>
    static object[] _data = new object[10];

    /// <summary>
    /// C# doesn't define when this constructor is run, but it will 
    /// be run right before it is used most likely.
    /// </summary>
    static SiteStatic()
    {
        // Initialize all of our static members.
    }
}
 
You can use static classes to store single-instance, global data. The class will be initialized at any time, but it is my experience that it is initialized lazily, meaning at the last possible moment. However, you lose control over the exact behavior of the class by using a static class.

Singleton Advantages

Singletons preserve the conventional class approach, and don't require that you use the static keyword everywhere. They may be more demanding to implement at first, but will greatly simplify the architecture of your program. Unlike static classes, we can use singletons as parameters or objects.
// We want to call a function with this structure as an object.
// Get a reference from the Instance property on the singleton.
{
    SiteStructure site = SiteStructure.Instance;
    OtherFunction(site); // Use singleton as parameter.
}
 

Interface Inheritance

In C#, an interface is a contract, and objects that have an interface must meet all of the requirements of that interface. Usually, the requirements of the interface are a subset of the object in question. Here is how we can use a singleton with an interface, which in the example is called ISiteInterface.
/// <summary>
/// Stores signatures of various important methods related to the site.
/// </summary>
public interface ISiteInterface
{
};

/// <summary>
/// Skeleton of the singleton that inherits the interface.
/// </summary>
class SiteStructure : ISiteInterface
{
    // Implements all ISiteInterface methods.
    // [omitted]
}

/// <summary>
/// Here is an example class where we use a singleton with the interface.
/// </summary>
class TestClass
{
    /// <summary>
    /// Sample.
    /// </summary>
    public TestClass()
    {

        // Send singleton object to any function that can take its interface.
        SiteStructure site = SiteStructure.Instance;
        CustomMethod((ISiteInterface)site);
    }

    /// <summary>
    /// Receives a singleton that adheres to the ISiteInterface interface.
    /// </summary>
    private void CustomMethod(ISiteInterface interfaceObject)
    {
        // Use the singleton by its interface.
    }
}
Now we can reuse our singleton for any of the implementations of interface-conforming objects. There may be 1, 2, or 10. We don't need to rewrite anything over and over again. We store state more conventionally, use objects by their interfaces, and can use traditional object-oriented programming best practices.