Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
What's a Singleton?
Message
 
To
10/08/2009 19:29:07
Timothy Bryan
Sharpline Consultants
Conroe, Texas, United States
General information
Forum:
ASP.NET
Category:
Class design
Miscellaneous
Thread ID:
01417218
Message ID:
01417226
Views:
63
>>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

Why not just create a static class?
Everything makes sense in someone's mind
public class SystemCrasher :ICrashable
In addition, an integer field is not for irrational people
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform