Example for Singleton Pattern

This code sample explains how to construct and use Singleton objects. The first example gives how to define the pattern. Followed by this is an example on how to obtain reference to such object. The third example calls methods on the object.

SINGLETON PATTERN IMPLEMENTATION


#region Singleton Pattern
// SINGLETON PATTERN IMPLEMENTATION
private static SqlConnection conn = null;

public static SqlConnection Instance()
{
if (conn == null)
{
conn = new SqlConnection(SQLHelper.CONN);
}
return conn;
}
#endregion


NORMAL CALL FOR REFERENCE

#region NORMAL CALL FOR REFERENCE
// Do not use this
// Normal Implementation - This code has to be replaced by singleton pattern
using (SqlConnection conn = new SqlConnection(SQLHelper.CONN))
#endregion


SINGLETON CALL

#region SINGLETON CALL
// SINGLETON CALL
using (Instance())
{
conn.Open();
using (SqlTransaction trans = conn.BeginTransaction())
{
try
{
SQLHelper.ExecuteNonQuery(trans, CommandType.StoredProcedure, INSERTSIGNON, signOnParms);
SQLHelper.ExecuteNonQuery(trans, CommandType.StoredProcedure, INSERTACCOUNT, addressParms);
trans.Commit();

}
catch
{
trans.Rollback();
throw;
}
}
}
#endregion


Comments

Author: pradipta17 Aug 2008 Member Level: Gold   Points : 2

This is not correct way of implementing singleton pattern.The method is not thread safe ,so there is a chance of multiple instances.See the following line

if (conn == null) { conn = new SqlConnection(SQLHelper.CONN); }

suppose two threads executing the above statements simultaneously then there is a chance of multiple instances.

Guest Author: Kimseng14 Jul 2012

Dear Sir,

Singleton is one time create the object, so if we do the same action again, it means that singleton will not create the object again. right? If it is that. It means that the memory not release this object.

And we dispose that object and set to null then when we do the same action again it will go to instantiate object again.

So it is not the purpose of singleton pattern.

Please give me any advice.

Thanks



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: