Reputation: 49
I'm wondering what the differences are between these two singleton classes. My professor showed us the last one said it was more flexible and better in it's performance. I'm also wondering why my professors version has a private constructor, can someone clearify why that is?
Version 1 - my version (standard I believe):
public class Singleton {
public static Singleton GetInstance() {
return Singleton.instance ?? (Singleton.instance = new Singleton());
}
Version 2 - flexible and high-performance:
public class Singleton {
private Singleton() {} // Why this?
private static class SingletonHolder() {
public static readonly Singleton instance = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.instance;
}
}
Upvotes: 2
Views: 94
Reputation: 1673
In c#, Private Constructor is a special instance constructor and it is used in a classes that contains only
static
members. If a class contains one or more private constructors and no public constructors, then the other classes are not allowed to create an instance for that particular class except nested classes.
constructor is private
, Because we don't want any outer class create an instance of this class.
and about performance, in version 1
you have to check: if instance of class is empty then create an instance, But in version 2
you have a static
constructor with a readonly
field, that mean the instance will be initialized when class call for the first time and for the next call static constructor never called again.
For more explanation about singleton
pattern, you can follow this link
Upvotes: 1
Reputation: 8937
The constructor is private to prevent others from instantiating the class explicitly, thereby strictly enforcing the singleton pattern.
As for the nested class, it makes it lazy and thread-safe without requiring locks. Flexibility and High-Performance are semantics on top of those primary benefits. (I mean, if you really want high performance you should be coding C or C++, for real). Jon Skeet explains it here. https://csharpindepth.com/articles/Singleton (Fifth version)
In this day and age, Version 1 isn't exactly standard, most of the libraries use the System.Lazy<T>
wrapper which manages lazyness without the boilerplate of nested classes.
Upvotes: 2