This design pattern is come under Creational Pattern in .Net. It is pattern is one of the simplest design patterns. This pattern ensures that a class has only one instance.Make the class of the single instance object responsible for creation, initialization, access, and enforcement. Declare the instance as a private static data member. Provide a public static member function that encapsulates all initialization code, and provides access to the instance. We can use the pattern for creating / controlled access for an object. The below example shows the implementation for this one.
Real time usage
Dbconnection , Utility projects, etc.
Example
Singleton Instance
---------------------------
Connect………….!
Connect………….!
Disconnect………….!
Singleton Instance
---------------------------
Connect………….!
Disconnect………….!
Real time usage
Dbconnection , Utility projects, etc.
Example
// .NET guarantees thread safety for
static initialization
private
static SingletonConnaction
instance = null;
SqlConnection
sqlConnection = null;
private
SingletonConnaction()
{
//To DO:
Remove below line
Console.WriteLine("Singleton Instance ");
Console.WriteLine("-----------------");
//Replace
the Connection string by the below string.
sqlConnection = new SqlConnection();
}
// Lock
synchronization object
private
static object
syncLock = new object();
/// <summary>
/// DB Connection Object.
/// </summary>
public static SingletonConnaction
DBConnection
{
get
{
//
Support multithreaded applications through
lock
(syncLock)
{
if
(SingletonConnaction.instance == null)
SingletonConnaction.instance = new
SingletonConnaction();
return
SingletonConnaction.instance;
}
}
}
public void Connect()
{
Console.WriteLine("Connect.......!");
}
public void Disconnect()
{
sqlConnection.Dispose();
instance = null;
Console.WriteLine("DisConnect.......!");
}
We can call this method from one main function .You can see the
object created only the instance became null.
//Connecting to
SQL/Initialize SQL Connection
SingletonConnaction.DBConnection.Connect();
//Reuse
Existing Connection
SingletonConnaction.DBConnection.Connect();
//Disconnecting
Connection
SingletonConnaction.DBConnection.Disconnect();
//ReConnecting
to SQL/ReInitialize SQL Connection
SingletonConnaction.DBConnection.Connect();
SingletonConnaction.DBConnection.Disconnect();
Console.ReadLine();
Output:Singleton Instance
---------------------------
Connect………….!
Connect………….!
Disconnect………….!
Singleton Instance
---------------------------
Connect………….!
Disconnect………….!
No comments:
Post a Comment