over 9 years ago
Hello Friends,
This blog explains how to implement singleton design pattern in c#. So lets start with few basic things:--
What is Singleton ?
A singleton is a class which only allows one instance of itself to be created - and gives simple, easy access to instance.They fall in to the Creational patterns categories.
What does Singleton Offer ?
The Singleton pattern restricts the class to be instantiated only once and has a global point of access. In other words you can say class is static but can be instantiated.
Instance Control:- Singleton creates only one instance and prevents any further copies, and ensure that all object access the single instance.
Flexibility:- In singleton class controls the instantiation process.
Parameters:- Singleton class can be used as parameters or objects.
How it can be implemented ? You need to follow these steps to create a singleton pattern.
Instantiate an object and assign it to the private variable.
Example:- If you are designing a logging system then only one instance of logger is required to handle the log requests coming from different sources.
- public class Singleton
- {
- private static Singleton instance ; //Private static object declaration
- //Private construction declaration for prevent object creation
- private Singleton ()
- {
- }
- //A public property to access outside of the class to create an object
- public static Singleton Instance
- {
- get
- {
- if(instance==null)
- {
- instance= new Singleton();
- }
- return instance;
- }
- }
- }
public class Singleton { private static Singleton instance ; //Private static object declaration //Private construction declaration for prevent object creation private Singleton () { } //A public property to access outside of the class to create an object public static Singleton Instance { get { if(instance==null) { instance= new Singleton(); } return instance; } } }
0 Comment(s)