Skip to content

Instantly share code, notes, and snippets.

@ndamulelonemakh
Last active November 3, 2020 16:37
Show Gist options
  • Select an option

  • Save ndamulelonemakh/711864a49b1854fa13e286cb54ba09e5 to your computer and use it in GitHub Desktop.

Select an option

Save ndamulelonemakh/711864a49b1854fa13e286cb54ba09e5 to your computer and use it in GitHub Desktop.
C# Design Pattern Examples
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++;
}
}
/// <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