- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to implement a Singleton design pattern in C#?
Singleton Pattern belongs to Creational type pattern
Singleton design pattern is used when we need to ensure that only one object of a particular class is Instantiated. That single instance created is responsible to coordinate actions across the application.
As part of the Implementation guidelines we need to ensure that only one instance of the class exists by declaring all constructors of the class to be private. Also, to control the singleton access we need to provide a static property that returns a single instance of the object.
Example
Sealed ensures the class being inherited and object instantiation is restricted in the derived class
Private property initialized with null
ensures that only one instance of the object is created
based on the null condition
Private constructor ensures that object is not instantiated other than with in the class itself
Public method which can be invoked through the singleton instance
public sealed class Singleton { private static int counter = 0; private static Singleton instance = null; public static Singleton GetInstance { get { if (instance == null) instance = new Singleton(); return instance; } } private Singleton() { counter++; Console.WriteLine("Counter Value " + counter.ToString()); } public void PrintDetails(string message) { Console.WriteLine(message); } } class Program { static void Main() { Singleton fromFacebook = Singleton.GetInstance; fromFacebook.PrintDetails("From Facebook"); Singleton fromTwitter = Singleton.GetInstance; fromTwitter.PrintDetails("From Twitter"); Console.ReadLine(); } }
Output
Counter Value 1 From Facebook From Twitter