Рет қаралды 8,032
"Singleton pattern ensures a class has only one instance and provides a global point of access to it."
Thumb rule:
1. Declare a private constructor for the class.
2. Declare a static member for that class.
3. Create a static method for that class.
www.vapstudent.in
Links:
NodeJs MySQL API - • API CRUD - NodeJs + Ex...
NodeJs MongoDB API - • API CRUD - NodeJS + E...
//Library.cs - Class
using System;
namespace SigletonDemo
{
public class Library
{
private static int counter = 0;
private Library()
{
counter++;
Console.WriteLine("Counter Value : " + counter.ToString());
}
public static Library objInstance;
private static readonly object mylockobject = new object(); //Multi threaded
public static Library GetInstance()
{
lock (mylockobject)
{
if (objInstance == null)
objInstance = new Library();
}
return objInstance;
}
public string getBookDetails()
{
return "The Secret - written by Rhonda Byrne.";
}
public string getBook1Details()
{
return "Thulazi - written by Balakumaran.";
}
}
}
//Book.cs - Class
using System;
namespace SigletonDemo
{
public class Book
{
static void Main(string[] args)
{
Library book = Library.GetInstance();
Library book1 = Library.GetInstance();
string sBookName = book.getBookDetails();
string sBook1Name = book1.getBook1Details();
Console.WriteLine(sBookName);
Console.WriteLine(sBook1Name);
Console.ReadLine();
}
}
}