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
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.