>>>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?
If you created a static class, then methods could still be called many times from many places. Not what I want if I only want to pass around a single instance that is connected to my device. I always want THE instance that is connected and firing events from the device like Position Update from a GPS or on NewTagAddes for a Rfid reader.
Tim
Timothy Bryan