Created
December 25, 2018 22:51
-
-
Save vatbub/f4e63985f10ed0ecc2923b89f4418f9d to your computer and use it in GitHub Desktop.
A Singleton superclass in C#
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; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text.RegularExpressions; | |
namespace SingletonDemo | |
{ | |
public class Program | |
{ | |
public static void Main(string[] args) | |
{ | |
SampleClass.Instance.Test(); | |
} | |
} | |
public class Singleton<TSubclass> where TSubclass:Singleton<TSubclass>, new() // das new zwingt die Subklasse, einen parameterlosen Konstruktor zu haben | |
{ | |
private static TSubclass _instance; | |
public static TSubclass Instance | |
{ | |
get | |
{ | |
if (_instance == null) | |
_instance = new TSubclass(); | |
return _instance; | |
} | |
} | |
} | |
public class SampleClass : Singleton<SampleClass> | |
{ | |
public void Test() | |
{ | |
Console.WriteLine("Hello world from the singleton"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment