C#: Singleton Design Pattern with Quick code snippet

Objective

Singleton pattern provides a global, single instance by making the class create a single instance of itself.

Allowing other objects to access this instance through a class method that returns a reference to the instance. A class method is globally accessible.

Singleton Class Code Snippet

Declaring the class constructor as private so that no other object can create a new instance.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace singleton
{
    public sealed class Singleton
    {
        private static volatile Singleton instance;
        private static object syncRoot = new Object();
        static int instanceCounter;
        private Singleton() {
            
        }
        public static Singleton Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (syncRoot)
                    {
                        if (instance == null)
                            instance = new Singleton();
                    }
                }
                return instance;
            }
        }
        public int getCounter()
        {
            return instanceCounter++;
        }
    }
}

Calling class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace singleton
{
    class Program
    {
        static void Main(string[] args)
        {
            var counter = Singleton.Instance;
            var test = counter.getCounter();
                      
        }
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s