Friday, September 25, 2009

Design Patterns – Singleton Pattern

The Singleton pattern gives us a way to restrict the instantiation of objects of given class to certain number, in the common usage to one only.

The Singleton class instantiates itself and works as a global repository for an instance of itself. For example we share a database connection or log writer across all threads in one process.

Implementation of Singleton pattern



Here i'm going to implement Singleton class in C#. The class should hide its constructor. It has also GetInstance() method that gives back the only concrete instance. We embed the concrete instance of the class into the static variable "obj".

For the purpose of the demonstration we have one public method Add() used to add some number to the class and Total() which gives back the total of the added numbers.



public class Singleton
{
private static Singleton obj = new Singleton(); // holds a reference to the only concrete instance

private static int total = 0; // we add numbers up to this via Add()

private Singleton() { } // hiden constructor

public static Singleton GetInstance() { return obj; } // returns the only concrete instance

public void Add(int number)
{ // add up to the total
lock (obj) // synchronize in concurrency
{
Thread.Sleep(new Random().Next(1000)); // randomly wait up to a second
total += number;
Console.WriteLine(String.Format("Add {0} to total", number));
}
}

public int Total()
{ // gets the total
lock (obj)
return total;
}
}




In Add() method we have a timeout up to a second to randomize the time to run the method.

We also locked the access to the class variables for concurrency. We are going to test the Singletion class in multithreaded environment.


Usage of Singleton pattern




First we create three static helper methods which will make calls to Add() with different number from one to three.



class Program
{
// add
static void HelperOne() { Singleton.GetInstance().Add(1); }
static void HelperTwo() { Singleton.GetInstance().Add(2); }
static void HelperThree() { Singleton.GetInstance().Add(3); }
...



Then in Main() we run three threads and run concurrently the three static helper methods.

We wait for the threads to finish and show the total of all additions to the singleton class.




static void Main(string[] args)
{
Thread[] threads = new Thread[]
{
new Thread(new ThreadStart(HelperOne)),
new Thread(new ThreadStart(HelperTwo)),
new Thread(new ThreadStart(HelperThree))
};

foreach (Thread thread in threads) { thread.Start(); }
foreach (Thread thread in threads) { thread.Join(); }

Console.WriteLine(String.Format("The total is {0}",
Singleton.GetInstance().Total()));

Console.Read();

}



Run the example



Running that I've got the following output:




Happy codding!

Atanas Hristov


Shout it

No comments:

Post a Comment