Singleton Pattern Demo : Singleton Pattern : Design Patterns C# Source Code


Custom Search

C# Source Code » Design Patterns » Singleton Pattern »

 

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

    }
}

 
    
   
  
   







HTML code for linking to this page:

Follow Navioo On Twitter

C# Source Code

 Navioo Design Patterns
» Singleton Pattern