Created
November 24, 2023 13:53
-
-
Save sunmeat/a029e35f9598af4bfae27285091d959d to your computer and use it in GitHub Desktop.
singleton pattern C# example
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
class Singleton | |
{ | |
private static Singleton instance; | |
private int value; | |
private Singleton() | |
{ | |
value = 50; | |
} | |
public static Singleton GetInstance() | |
{ | |
return instance ?? (instance = new Singleton()); | |
} | |
public int GetValue() | |
{ | |
return value; | |
} | |
public void SetValue(int value) | |
{ | |
this.value = value; | |
} | |
} | |
class Program | |
{ | |
static void Main() | |
{ | |
var instance = Singleton.GetInstance(); | |
Console.WriteLine(instance.GetValue()); | |
instance.SetValue(75); | |
Console.WriteLine(instance.GetValue()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment