[Design Patterns] Singleton

Singleton restricts the instantiation of a class to one object. It is the one of the basic design patterns and easy to implement.

 

1. Singleton

A Singleton pattern ensures a class only has one instance, and provides a global point of access to it. [Gamma+] The way of make a class that can have only one instance is to embed a static variable and a static method inside the class.

 

2. Design

 

3. Implementation

  • private static instance
  • private constructor
  • public static method to return the unique instance of a class
public class SingletonClass
{
  private static SingletonClass uniqueInstance = null;
  private SingletonClass() { }
  public static SingletonClass getInstance()
  {
    if (uniqueInstance == null)
    {
      uniqueInstance = new SingletonClass();
    }
    return uniqueInstance;
  }
}

 

4. Consequences

  • insures that only one instance of the class can ever be created
  • access to the sole instance is strictly controlled by the object itself

 

5. Example

public class Phone
{
  public String Name { get; set; }
  public String Number { get; set; }
}

 

// Singleton
public class PhoneBook : List<Phone>
{
  // private instance
  private static PhoneBook uniqueInstance = null;
  /* private constructor
  It's impossible to instantiate this class outside the class */
  private PhoneBook()
  {
    Console.WriteLine("A Phonebook object is created");
  }
  /* public method is the only way to get PhoneBook object */
  public static PhoneBook getInstance()
  {
    if (uniqueInstance == null)
    {
      // first time
      uniqueInstance = new PhoneBook();
    }
    return uniqueInstance;
  }

  public string GetPhoneNumber(string name)
  {
    string number = (from p
      in uniqueInstance
      where p.Name == name
      select p.Number).SingleOrDefault();
  return number ?? "N/A";
  }
}

 

public class PhoneTest
{
  public static void TestPhoneBook()
  {
    Phone[] phones = {
      new Phone { Name = "Mike", Number = "123-4567"},
      new Phone { Name = "Jane", Number = "777-2345"},
      new Phone { Name = "Tomas", Number = "039-4832"} };
    for (int i=0; i<3; i++)
    {
      PhoneBook.getInstance().Add(phones[i]);
    }
    Console.WriteLine(" Mike's phone number : {0}",
      PhoneBook.getInstance().GetPhoneNumber("Mike"));
    Console.WriteLine(" Jane's phone number : {0}",
      PhoneBook.getInstance().GetPhoneNumber("Jane"));
    Console.WriteLine(" Nobodys's phone number : {0}",
      PhoneBook.getInstance().GetPhoneNumber("Nobody"));
  }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s