Csharp/C Sharp/Design Patterns/Singleton Pattern
Версия от 15:31, 26 мая 2010; (обсуждение)
Singleton Pattern Demo
using System;
sealed class MyClass {
private static bool instanceFlag = false;
public static MyClass GetMyClass() {
if (!instanceFlag) {
instanceFlag = true;
return new MyClass();
} else {
throw new Exception("An engine has already been created!");
}
}
private MyClass() {
Console.WriteLine("An MyClass");
}
}
class Client {
static void Main(string[] args) {
Console.WriteLine("Attempting to get first engine");
try {
MyClass eng = MyClass.GetMyClass();
} catch (Exception e) {
Console.WriteLine(e.Message);
}
Console.WriteLine("Attempting to get second engine");
try {
MyClass eng = MyClass.GetMyClass();
} catch (Exception e) {
Console.WriteLine(e.Message);
}
}
}