By using the Singleton design pattern you ensure that a class has only one instance. The instance operation is provided by the class itself. So it maintains its own unique instance.
The .NET framework offers a very simple and thread-safe way to create a Singleton. The following source code shows an according example, how to create a singleton instance for logging purposes.
At first we define a interface.
public interface ILogger { void Log(string message); }
Second we can implement the Singleton object. The class instance is provided by a property which returns a read only object. The .NET framework ensures a thread-safe and lazy creation of the class instance.
public class Logger : ILogger { private static readonly Logger _instance = new Logger(); private Logger() { } public static Logger Instince { get { return _instance; } } public void Log(string message) { throw new NotImplementedException(); } }
And the last code example shows how to use the Singleton within an demo application.
static void Main(string[] args) { ILogger logger; logger = Logger.Instince; logger.Log("foo"); }