Sunday, March 7, 2010

Singleton Pattern

I thought this would be a good design pattern to start with.

Little info :

Name                     : Singleton
Type                      : "Creational"
Description            : This design patterns let only a single object to be created for a particular class. All the                                 communication to that class is done via that single object.

Real World Usage

GSM Modem Connected via USB Port
This is a scenario which I came across during my internship program. There I was given a  task to develop a module which can be used to do the mobile communication of an online trading portal. The system needs to receive SMSs from users at anytime and need to send SMS to users according to the requests made by users. But if you use two objects to send and receive SMS, simply the system will fail, due to the fact that, you have only one port with a modem. Once you open that port for either sending or receiving, you can't open it again for the other operation. Therefore in such cases it is good practice to adhere to Singleton. Since singleton allows only one instance to be available from a particular class, you can use that instance for both send and receive operations.

Sample code is given below.

class SMS
{
     private static SMS smsObj;
     protected SMS()
    {
      // Do the initialization of modem port.
    }

    public static SMS GetObject()
    {
        if (smsObj == null)
       {
            smsObj = new SMS();
       }
       return smsObj ;
    }
}

class InPut
{
     public InPut()
     {
      SMS sms = SMS.GetObject();
     // receive sms.
     }
}

class OutPut
{
     public OutPut()
     {
      SMS sms = SMS.GetObject();
     // send sms.
     }
}

No comments:

Post a Comment