Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
What's a Singleton?
Message
De
10/08/2009 19:29:07
Timothy Bryan
Sharpline Consultants
Conroe, Texas, États-Unis
 
Information générale
Forum:
ASP.NET
Catégorie:
Conception classe
Divers
Thread ID:
01417218
Message ID:
01417223
Vues:
80
>What's a Singleton? An example would be nice?


Here is an example. I hear this was one of the most over used patterns but there are times when this is the best way to keep from having multiple instances of a class. For a good example, I often work with devices such as a Gps or an RFID reader. The class that talks to the device can only have a single instance because there can only be a single connection to the port the device is on. However I often need to subscribe to the events from the device class from multilple places. So I use a singleton pattern to always just get the instance of the existing class if it already exists. It looks like this:
public class GpsWrapper : System.ComponentModel.Component
{

#region Singleton

private static GpsWrapper instance = null;
public static GpsWrapper Instance
{
     get
     {
          if(instance == null)
               instance = new GpsWrapper();

          return instance;
     }
}

/// <summary>
/// Constructor
/// Private due to Singleton use
/// </summary>
private GpsWrapper()
{
     this.Initialize();
}

#endregion Singleton
Notice the constructor is private so it can't be called from outside the class. When a class makes a call to this it references the singleton like this:
GpsWrapper Gps = GpsWrapper.Instance;
If the Gps already exists, the existing instance is passed back, otherwise it is created first.

I hope that helps
Tim
Timothy Bryan
Précédent
Suivant
Répondre
Fil
Voir

Click here to load this message in the networking platform