-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
55f893d
commit d64e956
Showing
1 changed file
with
44 additions
and
0 deletions.
There are no files selected for viewing
44 changes: 44 additions & 0 deletions
44
design_patterns/creational_patterns/singleton/singleton.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} | ||
|
||
} |