The singleton pattern

The singleton pattern is perhaps the most common pattern used by developers across the globe. This pattern basically defines a class for which only one (single) instance can exist.

You can have a class that is either global or static with all static methods so that you do not need to create any instance of this class and use it directly. This is okay but not considered a best practice generally, unless you are defining a stateless interface to expose an underlying OS APIs, such as subset win32 APIs or a native DLL or system library exposing its one-off APIs.

Singleton - If you want to have a stateful class whose only one instance should exist in the given software, then what you need is a singleton class. An example of this class can be a configuration class, which is accessed by many other client classes from within the application layer.

Moreover, some of the other design patterns can themselves be singletons in their implementation, for example, factory, builder, and prototype patterns. The façade pattern can also be implemented as a singleton since in most of the cases, only one façade object is required to be created. You will understand more when we read more about these other patterns as we move further in this chapter.

The following code shows a simple implementation of a singleton pattern:

    /// <summary> 
/// A very simple Singleton class
/// Its a sealed class just to prevent derivation that
could potentially add instances
/// </summary>
public sealed class SimpleSingleton
{
/// <summary>
/// Privately hidden app wide single static
instance - self managed
/// </summary>
private static readonly SimpleSingleton instance = new
SimpleSingleton();

/// <summary>
/// Private constructor to hinder clients to create
the objects of <see cref="SimpleSingleton"/>
/// </summary>
private SimpleSingleton() { }

/// <summary>
/// Publicly accessible method to supply the only
instace of <see cref="SimpleSingleton"/>
/// </summary>
/// <returns></returns>
public static SimpleSingleton getInstance()
{
return instance;
}
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.126.199