CSharp - Design Patterns Singleton Pattern

Introduction

Singleton Pattern ensures that a class only has one instance, and provide a global point of access to it.

Demo

using System;

public sealed class Singleton
{
    private static readonly Singleton instance = new Singleton();
    private int numberOfInstances = 0;
    private Singleton()
    {/*  w ww  .j  ava  2  s  .  c  o m*/
        Console.WriteLine("Instantiating inside the private constructor.");
        numberOfInstances++;
        Console.WriteLine("Number of instances ={0}", numberOfInstances);
    }
    public static Singleton Instance
    {
        get
        {
            Console.WriteLine("We already have an instance now.Use it.");
            return instance;
        }
    }
}
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Trying to create instance s1.");
        Singleton s1 = Singleton.Instance;
        Console.WriteLine("Trying to create instance s2.");
        Singleton s2 = Singleton.Instance;
        if (s1 == s2)
        {
            Console.WriteLine("Only one instance exists.");
        }
        else
        {
            Console.WriteLine("Different instances exist.");
        }
    }
}

Result

Related Topics