Design patterns: Singleton

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");
}
Werbung
Dieser Beitrag wurde unter .NET, C#, Design Pattern veröffentlicht. Setze ein Lesezeichen auf den Permalink.

Kommentar verfassen

Trage deine Daten unten ein oder klicke ein Icon um dich einzuloggen:

WordPress.com-Logo

Du kommentierst mit deinem WordPress.com-Konto. Abmelden /  Ändern )

Facebook-Foto

Du kommentierst mit deinem Facebook-Konto. Abmelden /  Ändern )

Verbinde mit %s