C#Dot Net Perls

C#
Singleton Pattern vs. Static Class

by Sam Allen
Image of a 1.

Problem

Store common data that is only needed in one location, using a singleton or static class. You need to save state between usages and store some caches. The object must be initialized only once and shared in many code locations, as making a new object each time would be expensive.

C# Solution

There are important 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 and they should be used in different situations.

How can I implement a singleton?

Using language-specific features, such as the static keyword. Our ideal solution is called the singleton design pattern. As you know, a singleton is a single-instance object, and they simplify complex code. 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.
    }
}

How can I make a static class?

With the static keyword. 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.

What advantages does the singleton have?

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.
}

How can I use singletons with interfaces?

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.

Conclusion

Singletons allow us to reuse code and control object state much easier. This improves code-sharing, and results in a far cleaner body of code. With less code, your programs will usually have fewer bugs and will be easier to maintain. One good book about this topic is called C# Design Patterns and is written by Judith Bishop.

Dot Net Perls is dedicated to sharing code and knowledge. It has
© 2007-2008 Sam Allen. All rights reserved.

Ads by The Lounge