Tuesday, August 5, 2014

Implementing The Singleton Pattern in C#

If you’re wanting to have just one instance of a class in your project, the singleton pattern is your friend. This goal is achieved by encapsulating constructor of the class we wish to have one instance of, and providing a getter for an instance of it. There are various ways to do this. I’ll provide a thread-safe version here. ApplicationSettings is just a hypothetical class which I’ll use for demonstration purposes.

pattern singleton c# :

using System;

public class Singleton
{
   private static Singleton instance;

   private Singleton() {}

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

implement c#
/// <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. 
11./// <summary>
12./// Allocate ourselves. We have a private constructor, so no one else can.
13./// </summary>
14.static readonly SiteStructure _instance = new SiteStructure();
15. 
16./// <summary>
17./// Access SiteStructure.Instance to get the singleton object.
18./// Then call methods on that instance.
19./// </summary>
20.public static SiteStructure Instance
21.{
22.get return _instance; }
23.}
24. 
25./// <summary>
26./// This is a private constructor, meaning no outsides have access.
27./// </summary>
28.private SiteStructure()
29.{
30.// Initialize members, etc. here.
31.}
32.}

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.
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. 
11./// <summary>
12./// C# doesn't define when this constructor is run, but it will
13./// be run right before it is used most likely.
14./// </summary>
15.static SiteStatic()
16.{
17.// Initialize all of our static members.
18.}
19.}
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.
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.
01./// <summary>
02./// Stores signatures of various important methods related to the site.
03./// </summary>
04.public interface ISiteInterface
05.{
06.};
07. 
08./// <summary>
09./// Skeleton of the singleton that inherits the interface.
10./// </summary>
11.class SiteStructure : ISiteInterface
12.{
13.// Implements all ISiteInterface methods.
14.// [omitted]
15.}
16. 
17./// <summary>
18./// Here is an example class where we use a singleton with the interface.
19./// </summary>
20.class TestClass
21.{
22./// <summary>
23./// Sample.
24./// </summary>
25.public TestClass()
26.{
27. 
28.// Send singleton object to any function that can take its interface.
29.SiteStructure site = SiteStructure.Instance;
30.CustomMethod((ISiteInterface)site);
31.}
32. 
33./// <summary>
34./// Receives a singleton that adheres to the ISiteInterface interface.
35./// </summary>
36.private void CustomMethod(ISiteInterface interfaceObject)
37.{
38.// Use the singleton by its interface.
39.}
40.}
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 programmingbest 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.

source : http://blog.hamidnazari.com/2010/08/01/implementing-the-singleton-pattern-in-c-sharp/