What is Singleton Implementation in C#?
Deffination: Ensure a class has only one instance and provide a global point of access to it.
Examples:
To understand in detail about Singleton refer all examples or else one is enough to know about the actual need of it.
Sample code in C#This structural code demonstrates the Singleton pattern which assures only a single instance (the singleton) of the class can be created.
This real-world code demonstrates the Singleton pattern as a LoadBalancing object. Only a single instance (the singleton) of the class can be created because servers may dynamically come on- or off-line and every request must go throught the one object that has knowledge about the state of the (web) farm.
This .NET optimized code demonstrates the same code as above but uses more modern, built-in .NET features. Here an elegant .NET specific solution is offered. The Singleton pattern simply uses a private constructor and a static readonly instance variable that is lazily initialized. Thread safety is guaranteed by the compiler.
Now Let us Come to Adv & Dis Adv Of SingleTon
This implementation has two main advantages: Adv: Because the instance is created inside the Instance property method, the class can exercise additional functionality (for example, instantiating a subclass), even though it may introduce unwelcome dependencies. The instantiation is not performed until an object asks for an instance; this approach is referred to as lazy instantiation. Lazy instantiation avoids instantiating unnecessary singletons when the application starts.
Dis Adv:
The main disadvantage of this implementation, however, is that it is not safe for multithreaded environments. If separate threads of execution enter the Instance property method at the same time, more that one instance of the Singleton object may be created. Each thread could execute the following statement and decide that a new instance has to be created: |
No comments:
Post a Comment