onsdag 11 december 2013

Design Patterns: Singleton

The most basic of all design patterns is the singleton,

From Wikipedia, "In software engineering, the singleton pattern is a design pattern that restricts the Instantiation of a class to one object."

This means that we can only create ONE instance of a class and that instance should be reused.


public class MySingleton {
   private static MySingleton instance = null;
   protected MySingleton() {
      // Exists only to defeat instantiation.
   }
   public static MySingleton getInstance() {
      if(instance == null) {
         instance = new MySingleton();
      }
      return instance;
   }
}
As can be seen in the example code, this class is a static class containing static methods. When you want to create an instance of the singleton class you call MySingleton.getInstance().
This method check if the static field instance is null, and if it is null then it creates a new instance using the keyword new and return the new instance. In case there already is an instance, we return it directly.

We can't create an instance of MySingleton by using MySingleton myInstance = new MySingleton() since the constructor is defined as protected (only reachable from the class it self, and not by any other class)

Known uses:
- Logging class
- Utility classes


Singleton is considered bad in many cases but it is a fundamental design pattern that everybody should know about.

Inga kommentarer:

Skicka en kommentar