Singleton desing Pattern in C# with example
It is creational design pattern, as it deals with object creation and manipulation.
Here we are going to learn,
What is singleton desing pattern
When to use singleton design patterns / Why to use singleton design patterns
Real-time examples of Singleton design patterns
Advantages of singleton design patterns
Disadvantages of singleton design patterns
What is single design pattern
It ensures that only one instance of perticular class will be created and provide global access to that instance thoughout application.
If we want a class whose only one object can be created, then we use singleton class.
Why do we need only one object of class
Objects used for logging, device drivers for printers or registry settings need to have only one object. If we create multiple objects of this classes then program may end up with incorrect behavior or inconsistant results.
Advantages of singleton desgin pattern –
- It handels concurrent access to shared resouce.
- As it provides a single global point of access to a particular instance, so it is easy to maintain.
- To reduce the overhead of instantiating a heavy object again and again.
- It can be lazy loaded & static initialization.
- To share common data i.e. master data and configuration data which is not changed that frequently in an application. In that case, we need to cache the objects in memory.
Real Time example of singleton desing pattern:
Use for logger classes.
Use for common data to share in application like configuration etc.
Creating database connection though singleton class which will help to improve performance of the application, so no need to create object again and again.
Disadvantages of singleton desing pattern
Unit testing is very difficult due to static and global object.
Can not be used in multi-threaded program.