Last active
November 3, 2020 16:37
-
-
Save ndamulelonemakh/711864a49b1854fa13e286cb54ba09e5 to your computer and use it in GitHub Desktop.
C# Design Pattern Examples
This file contains hidden or 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
| public class SimpleSingleton{ | |
| private int count = 1; | |
| // Use lazy<T> to delay initialisation until the field is accessed | |
| private static readonly Lazy<SimpleSingleton> _instance = new Lazy<SimpleSingleton>( ()=> new SimpleSingleton()); | |
| private SimpleSingleton(){ | |
| Console.WriteLine($"{nameof(SimpleSingleton)} constructor called at {DateTime.Now}"); | |
| } | |
| public static SimpleSingleton Instance{ | |
| get => _instance.Value; | |
| } | |
| public int Count{get => count;} | |
| public void IncrementCount(){ | |
| count++; | |
| } | |
| } |
This file contains hidden or 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
| /// <summary> | |
| /// A simple 'thread-safe' Singleton implementation with no 'Lazy Loading' | |
| /// </summary> | |
| public class SimpleSingleton{ | |
| private int count = 1; | |
| private static readonly SimpleSingleton _instance = new SimpleSingleton(); | |
| private SimpleSingleton(){ | |
| Console.WriteLine($"{nameof(SimpleSingleton)} constructor called at {DateTime.Now}"); | |
| } | |
| public static SimpleSingleton Instance{ | |
| get => _instance; | |
| } | |
| public int Count{get => count;} | |
| public void IncrementCount(){ | |
| count++; | |
| } | |
| } | |
| // TEST CODE | |
| public class Program | |
| { | |
| public static void Main() | |
| { | |
| var obj1 = SimpleSingleton.Instance; | |
| var obj2 = SimpleSingleton.Instance; | |
| // Test that obj1 and obj2 are indeed point to the same instance of our SimpleSingleton | |
| Console.WriteLine(obj1.Count); | |
| obj1.IncrementCount(); | |
| // Count should now be incremented in 'both' objects | |
| Console.WriteLine(obj1.Count); | |
| Console.WriteLine(obj2.Count); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment