C# - Singleton Pattern vs. Static Classes

Link sent to me from Justin.. as we’ve been discussing using Singleton’s in Win Services for the previous post I talked about. I’ll convert to VB later.

Original Article: http://dotnet.dzone.com/news/c-singleton-pattern-vs-static-

By Sam Allen

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.

view source

print?

01./// <summary>

02./// Sample singleton object.

03./// </summary>

04.public sealed class SiteStructure

05.{

06. /// <summary>

07. /// Possible an expensive resource we need to only store in one place.

08. /// </summary>

09. object[] _data = new object[10];

10. /// <summary>

11. /// Allocate ourselves. We have a private constructor, so no one else can.

12. /// </summary>

13. static readonly SiteStructure _instance = new SiteStructure();

14. /// <summary>

15. /// Access SiteStructure.Instance to get the singleton object.

16. /// Then call methods on that instance.

17. /// </summary>

18. public static SiteStructure Instance

19. {

20. get { return _instance; }

21. }

22. /// <summary>

23. /// This is a private constructor, meaning no outsides have access.

24. /// </summary>

25. private SiteStructure()

26. {

27. // Initialize members, etc. here.

28. }

29.}

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.

view source

print?

01./// <summary>

02./// Static class example. Pay heed to the static keywords.

03./// </summary>

04.static public class SiteStatic

05.{

06. /// <summary>

07. /// The data must be a static member in this example.

08. /// </summary>

09. static object[] _data = new object[10];

10. /// <summary>

11. /// C# doesn't define when this constructor is run, but it will

12. /// be run right before it is used most likely.

13. /// </summary>

14. static SiteStatic()

15. {

16. // Initialize all of our static members.

17. }

18.}

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.

view source

print?

1.// We want to call a function with this structure as an object.

2.// Get a reference from the Instance property on the singleton.

3.{

4. SiteStructure site = SiteStructure.Instance;

5. OtherFunction(site); // Use singleton as parameter.

6.}

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.

view source

print?

01./// <summary>

02./// Stores signatures of various important methods related to the site.

03./// </summary>

04.public interface ISiteInterface

05.{

06.};

07./// <summary>

08./// Skeleton of the singleton that inherits the interface.

09./// </summary>

10.class SiteStructure : ISiteInterface

11.{

12. // Implements all ISiteInterface methods.

13. // [omitted]

14.}

15./// <summary>

16./// Here is an example class where we use a singleton with the interface.

17./// </summary>

18.class TestClass

19.{

20. /// <summary>

21. /// Sample.

22. /// </summary>

23. public TestClass()

24. {

25. // Send singleton object to any function that can take its interface.

26. SiteStructure site = SiteStructure.Instance;

27. CustomMethod((ISiteInterface)site);

28. }

29. /// <summary>

30. /// Receives a singleton that adheres to the ISiteInterface interface.

31. /// </summary>

32. private void CustomMethod(ISiteInterface interfaceObject)

33. {

34. // Use the singleton by its interface.

35. }

36.}

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

Here we can reuse code and control object state much easier. This allows you greatly improved code-sharing, and 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.

Quick Enum Snippet. Get Values or Names based on Name or Value

.Net – Improve garbage collection and performance