Search content within the blog

Sunday, May 8, 2011

Difference between a singleton and static in C#

Advantages of singletons

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.

Using singleton as parameter [C#]

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

Use singletons with interfaces

You can use singletons with interfaces just like any other class. In C#, an interface is a contract, and objects that have an interface must meet all of the requirements of that interface.

Singletons used with interface [C#]

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

Reusing the singleton. Here we can use the singleton on any method that accepts the interface. We don't need to rewrite anything over and over again.

No comments:

Post a Comment