Skip to content

Commit

Permalink
add implementation for singleton
Browse files Browse the repository at this point in the history
  • Loading branch information
saadati944 committed May 10, 2021
1 parent 55f893d commit d64e956
Showing 1 changed file with 44 additions and 0 deletions.
44 changes: 44 additions & 0 deletions design_patterns/creational_patterns/singleton/singleton.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
using System;
using System.Threading.Tasks;

namespace designPatterns
{
class Singleton
{
private static Singleton _singleton;

private readonly string message;

private Singleton()
{
message = $"this instance was created in {DateTime.Now.Hour}:{DateTime.Now.Minute}:{DateTime.Now.Second}:{DateTime.Now.Millisecond}";
}

public static Singleton GetInstance()
{
if (_singleton is null)
_singleton = new Singleton();
return _singleton;
}

public override string ToString()
{
return message;
}
}
class Program
{
static void Main(string[] args)
{
Singleton singleton1 = Singleton.GetInstance();
Console.WriteLine("get an instance of singleton class");
Console.WriteLine("singleton1=>"+singleton1);
Console.WriteLine("wait for 1 second");
Task.Delay(1000).Wait();
Console.WriteLine("trying to get another instance of it");
Singleton singleton2 = Singleton.GetInstance();
Console.WriteLine("singleton2=>"+singleton2);
}
}

}

0 comments on commit d64e956

Please sign in to comment.