Csharp/C Sharp/Design Patterns/Singleton Pattern

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

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);
        }
    }
}