Wednesday 20 February 2019

C# Singleton design pattern

Singleton design pattern: Singleton design pattern assures only one instance of one class. You can access that instance globally. Implementation of singleton design pattern is as following:


Step 1: Create interface with methods that you want to implement.
public interface IAccountService
{
string Login(string username, string password);
}

Step 2: Create singleton class as following and implement the above created interface.
/// <summary>
/// Singleton class with interface
/// </summary>
public sealed class AccountService : IAccountService
{
/// <summary>
/// Private constructor to prevent the class instance to be create
/// </summary>
private AccountService()
{
}

private static readonly AccountService instance = new AccountService();
public static AccountService Instance
{
get
{
return instance;
}
}

public string Login(string username, string password)
{
//Do logic logic here
return "Ok";
}
}

Step 3: Now use the AccountService singleton class as following:
public void Test()
{
IAccountService test = AccountService.Instance;

var tasks = new Task[2];
for (int i = 0; i < tasks.Length; i++)
{
tasks[i] = System.Threading.Tasks.Task.Run(() => test.Login("test", "test@321"));
}
System.Threading.Tasks.Task.WaitAll(tasks);
}

No comments:

Post a Comment