C# Singleton Pattern

The Singleton Design Pattern is the standard way programmers create classes which are designed to have one and only one instantiation at any point in time. These classes can be used for configurations or settings objects which are globally available and which need to maintain state when being read or updated by various portions of the application.

This is accomplished by making the class Constructor private so that it cannot be accessed. This stops the class from being instantiated by code external to the class itself. Then a public property is exposed which retrieves a reference to an existing instance of the class stored in a local variable or if an instance does not yet exist the class creates a new instance and saves the reference for later calls.

Example Code:

1 public sealed class MySingleton

2 {

3 private static volatile MySingleton instance;

4 private static object syncer = new Object();

5

6 private MySingleton() { }

7

8 public static MySingleton Instance

9 {

10 get

11 {

12 if (instance == null)

13 {

14 lock (syncer)

15 {

16 instance = new MySingleton();

17 }

18 }

19 return instance;

20 }

21 }

22 }

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s