Last active
September 29, 2019 18:41
-
-
Save IamLizu/628dfb7103cb970a09bdc60ae39e756f to your computer and use it in GitHub Desktop.
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
using System; | |
namespace OOP.Singleton | |
{ | |
class Singleton | |
{ | |
// holds the singleton instance | |
private static Singleton Instance; | |
public string text; | |
// private constructor so that Singleton class itself can call itself. | |
private Singleton (string text) | |
{ | |
this.text = text; | |
} | |
public static Singleton GetInstance(string text) | |
{ | |
// checks if instance is created | |
if (Instance == null) | |
{ | |
// if note create one | |
Instance = new Singleton(text); | |
} | |
// return the created instance on every subsequent call | |
return Instance; | |
} | |
} | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
Console.WriteLine("Demonstrates Singleton class. Output of the two print statement bellow will be same"); | |
Console.WriteLine("because the class returned the cached instance of the second call."); | |
Singleton one = Singleton.GetInstance("One"); | |
Singleton two = Singleton.GetInstance("Two"); | |
Console.WriteLine(one.text); | |
Console.WriteLine(two.text); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment