Friday 28 May 2010

Singletone Pattern

Making one instance of a class through out the project is called singletone. To do a object singletone you could make a class instance as static. Here is the technique to declare a object as singletone.

static BuilderInformation _Instance = null;

public static BuilderInformation GetInstance()

{

if (_Instance == null)

      {

            _Instance = new BuilderInformation();

}

return _Instance;

}     

When you need the object of this class just declare like:

 BuilderInformation builderInformation = BuilderInformation.GetInstance();

We can make collection of object as singletone. Here is an example of that. If SalesOfficeOID is not in the _LiveAgentConversationList list make an object of _ InstanceLA and append it to the collection of list.

static LiveAgentConversation _InstanceLA = null;

static IList<LiveAgentConversation> _LiveAgentConversationList = new List<LiveAgentConversation>();

public static LiveAgentConversation GetInstance(string saleOfficeOID)

{

LiveAgentConversation liveAgentConversation = null;

      if (_LiveAgentConversationList.Count > 0)

      {

            for (int i = 0; i <>

            {

                  if (_LiveAgentConversationList[i]._SalesOfficeOID == saleOfficeOID)

                  {

                        return _LiveAgentConversationList[i];

                  }            

            }

            if (liveAgentConversation == null)

            {

                liveAgentConversation = new LiveAgentConversation();

                liveAgentConversation._SalesOfficeOID = saleOfficeOID;               

                _LiveAgentConversationList.Add(liveAgentConversation);

            }

            return liveAgentConversation;

        }

}

During object invokation write statement like:

LiveAgentConversation liveAgentConversation = LiveAgentConversation. GetInstance(string saleOfficeOID)

3 comments:

  1. Your post is very helpful.
    Can u please describe the necessity of Single Tone Pattern...
    That will help me to understand when and why I shall use this pattern.

    ReplyDelete
  2. As you know naturally every time we make object by using new keyword to perform or invoke something. So huge amount of unused object occupy memory. Its slow down the web project performance. In web project when there is a memory management issue likes memory lickage could take place due to heavy operation, in that situation you can use this pattern. As you know garbage collector automatically collect unused object and free memory. But it takes time to run automatically. In that situation you may forcefully run garbage collector when any operation complete.
    GC.Collect();
    it also one way of memory management

    ReplyDelete