lundi 30 mars 2015

Simpler Singleton Pattern

I have been reviewing some code of some old projects and I found a singleton there. It is a requirement to use a singleton and I was thinking of a way to make it look "simpler" when using.


I found, it would be easier to access the methods and properties like a static class. So I basically implemented a singleton using static methods to skip the requirement to use GetInstance(). This is how I implemented it:



public class ExampleSingleton
{
string someRequiredValue = "This is an example.";

/// <summary>
/// Private Constructor
/// </summary>
private ExampleSingleton() { }
private static volatile ExampleSingletoninstance;

/// <summary>
/// !!! PRIVATE !!!
/// Instance Property.
/// Returns the instance of this singleton.
/// (ThreadSafe)
/// </summary>
private static ExampleSingleton Instance
{
get
{
if (instance == null)
{
lock (_lock)
{
if (instance == null)
{
instance = new ExampleSingleton();
}
}
}

return instance;
}
}

/// <summary>
/// Example field contains a value that should be
/// accessible from outside.
/// </summary>
public static string SomeRequiredField
{
get
{
// Here you do the job you would have to do "outside"
// of the class normally.
return ExampleSingleton.Instance.someRequiredValue;
}
}

// Helper for a secure thread synchronisation.
private static object _lock = new object();
}


So when you want to access the singleton values you can just do it like this:



// Access the values like this
string requiredField = ExampleSingleton.SomeRequiredField;

// Instead of this
string requiredField = ExampleSingleton.Instance.SomeRequiredField;

// Or even this
string requiredField = ExampleSingleton.GetInstance().SomeRequiredField;


Am I violating the principles of the singleton pattern here? It basically is still a singleton pattern but the work of getting the instance is done internally. What could be the con's of this example? Are there other pro's?


Thanks


Aucun commentaire:

Enregistrer un commentaire