Pages

Wednesday, September 9, 2009

Singleton Pattern

Source:- C-sharpcorner

Link:-

http://www.c-sharpcorner.com/UploadFile/questpond/DP109212008014904AM/DP1.aspx

There are situations in a project where we want only one instance of the object to be created and shared between the clients. No client can create an instance of the object from outside. There is only one instance of the class which is shared across the clients. Below are the steps to make a singleton pattern :-

  1. Define the constructor as private.
  2. Define the instances and methods as static.

Below is a code snippet of a singleton in C#. We have defined the constructor as private, defined all the instance and methods using the static keyword as shown in the below code snippet figure 'Singleton in action'. The static keyword ensures that you only one instance of the object is created and you can all the methods of the class with out creating the object. As we have made the constructor private, we need to call the class directly.

Figure 24. Singleton in action
Note : In JAVA to create singleton classes we use the STATIC keyword , so its same as in C#. You can get a sample C# code for singleton in the 'singleton' folder.

When you are using singleton pattern becareful about the threading, there might be some cases two threads may try to use the same object in that case application will end up having wired results.

Use the following code

object cacheLocker = new object();

lock (cacheLocker)
           {
           // Actual thread safe code   

           }

Are you can use Monitor class as well

 private readonly System.Threading.ReaderWriterLockSlim LockObj = new System.Threading.ReaderWriterLockSlim();

        public void Add(T item)
        {
            this.LockObj.EnterWriteLock();
            try
            {
                if(this.InternalCache.Count == 10)
                    this.InternalCache.RemoveLast();

                this.InternalCache.AddFirst(item);
            }
            finally
            {
                this.LockObj.ExitWriteLock();
            }
        }

0 comments: