Sprache: C#
Das Singelton-Pattern ist wohl eins der einfachsten und praxisrelevantesten Designpatterns.
Hier also einmal eine beispielhafte Implementierung in C#
public class Singelton
{
private static Singelton me = null;
static readonly object padlock0 = new object(); //Zur Threadsicherheit
private Singelton()
{
//Initialize
}
public static Singelton GetInstance()
{
lock (padlock0)
{
if(me == null)
{
me = new Singelton();
}
return me;
}
}
}
public class Singelton
{
private static Singelton me = null;
static readonly object padlock0 = new object(); //Zur Threadsicherheit
private Singelton()
{
//Initialize
}
public static Singelton GetInstance()
{
lock (padlock0)
{
if(me == null)
{
me = new Singelton();
}
return me;
}
}
}
Alte URL:
/snippet/singelton-in-c-threadsicher-implementiert/1063
Warum so umständlich?
[code]public static readonly Singleton Instance = new Singleton();[/code]
Sorry, Michael, das ist Quatsch. Der Punkt ist ja, dass das Singleton threadsicher sein soll.
OP:
1. Das Teil heißt Singleton.
2. Du hast folgendes vergessen zu erwähnen:
2a. Diese Klasse darf [b]kein einziges[/b] public-Member haben.
2b. [b]Jede public Methode[/b] – auch static, sofern sie auf die Instanz zugreifen – dieser Klasse muss am padlock0 synchronisiert werden, weil sonst die Aufrufe nicht atomar sind.