16.9 Implement the Singleton Pattern


Problem

You need to ensure that only a single instance of a type exists at any given time and that the single instance is accessible to all elements of your application.

Solution

Implement the type using the "Singleton Pattern" by

  • Implementing a private static member within the type to hold a reference to the single instance of the type.

  • Implementing a publicly accessible static property in the type to provide read-only access to the singleton instance.

  • Implementing a private constructor so that code can't create additional instances of the type.

Discussion

Of all the identified patterns, the Singleton Pattern is perhaps the most widely known and commonly used. The purpose of the Singleton Pattern is to ensure that only one instance of a type exists at a given time and to provide global access to the functionality of that single instance. The following code demonstrates an implementation of the Singleton Pattern for a class named SingletonExample :

 public class SingletonExample {     // A static member to hold a reference to the singleton instance     private static SingletonExample instance;     // A static constructor to create the singleton instance. Another     // alternative is to use lazy initialization in the Instance property.     static SingletonExample () {         instance = new SingletonExample();         }              // A private constructor to stop code from creating additional      // instances of the singleton type     private SingletonExample () {}          // A public property to provide access to the singleton instance     public static SingletonExample Instance {                   get { return instance; }     }          // Public methods that provide singleton functionality     public void SomeMethod1 () { /*..*/ }     public void SomeMethod2 () { /*..*/ } } 

To invoke the functionality of the SingletonExample class, you can obtain a reference to the singleton using the Instance property and then call its methods. Alternatively, you can execute members of the singleton directly through the Instance property. The following code shows both approaches.

 // Obtain reference to singleton and invoke methods SingletonExample s = SingletonExample.Instance; s.SomeMethod1();          // Execute singleton functionality without a reference SingletonExample.Instance.SomeMethod2(); 



C# Programmer[ap]s Cookbook
C# Programmer[ap]s Cookbook
ISBN: 735619301
EAN: N/A
Year: 2006
Pages: 266

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net