I am following a MSDN article to understand the single ton design pattern. I have few questions with respect to the approach they followed.
IN THE SECOND APPROACH Static Initialization
- it is not clear to me why this class was declared as sealed.
why did they mark the private instance variable( instance ) as readonly ?
The class was not declared as static, but as sealed (other classes can’t subclass it). It’s done because the singleton implementation in question knows to instantiate only instances of this specific class.
If you subclass it:
public class Child: Singleton { ... }the Child class will still instantiate the base class:
Child.Instancewill still return instance of Singleton), which will result in confusing code.
The readonly increases code readability and prevents mistakes in future modification of the class.