Singleton implemented with C# could be like:
public class Singleton
{
private static Singleton instance;
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
If I use static to implement it like:
public static class Globals{
public static Singleton Instance = new Singleton();
}
in this way, app should also only get the one instance for the entire app. So what's the difference between these 2 approaches? Why not use static member directly(more simple and straight forward)?
If you use the second approach:
public static class Globals{
public static Singleton Instance = new Singleton();
}
There's nothing preventing somebody from doing:
Singleton anotherInstance = new Singleton(); // Violates singleton rules
You also don't get the same lazy initialization your first version (attempts to) achieve, plus you're using a public field, which doesn't allow you the same flexibility in the future if you need to change what happens when a value is fetched.
Note that .NET 4 provides a potentially better approach to making a singleton:
public class Singleton
{
private static readonly Lazy<Singleton> instance = new Lazy<Singleton>( ()=> new Singleton());
private Singleton() {}
public static Singleton Instance
{
get
{
return instance.Value;
}
}
}
This is nice because it's fully lazy and fully thread safe, but also simple.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With