0 Tage Serie
csharp / beginner
Snippet

Globale Instanz-Koordination

Das Singleton-Muster stellt sicher, dass eine Klasse nur eine Instanz hat und bietet einen globalen Zugriffspunkt darauf. Dies ist nützlich für die Verwaltung von gemeinsam genutztem Status wie Anwendungseinstellungen.

snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
public class ConfigurationManager
{
// A static property that holds the single instance
public static ConfigurationManager Instance { get; } = new ConfigurationManager();
// Private constructor prevents other classes from creating new instances
private ConfigurationManager() { }
public string AppName = "MyCSharpApp";
}
Erklärung
1
public static ConfigurationManager Instance { get; } = new ConfigurationManager();
Erstellt die einzige Instanz dieser Klasse.
2
private ConfigurationManager() { }
Verhindert die Instanziierung von außerhalb der Klasse über das 'new'-Schlüsselwort.