Singleton Pattern   «Prev  Next»
Lesson 6Singleton: participants and collaborations
ObjectiveClasses comprise a Singleton and Clients interface with Singleton.

Classes comprise a Singleton and Clients interface with Singleton

The Singleton is a particularly simple pattern because it only has one class and two responsibilities. Thus, its participant list looks like this:
  1. Singleton
  2. Create the unique instance
  3. Provide a reference or pointer to that instance
Most patterns have much larger participant lists.

Collaborations

Singleton is such a simple pattern that it really does not say much about collaborations. Its collaborations list looks like this:
  1. Clients use the getInstance() method to get a pointer or reference to the unique instance of the Singleton.
A client is any object or class outside the pattern; generally one that only knows about the public interface that the pattern and its classes present, rather than about its private implementation.


Singleton With No Subclassing

  1. First, let us look at the case where we are not concerned with subclassing the Singleton class
  2. We will use a static method to allow clients to get a reference to the single instance

Class Singleton is an implementation of a class that only allows one instantiation. There is private reference to the one and only instance. The Singleton returns a reference to the single instance and creates the instance if it does not yet exist. This is called lazy instantiation. The Singleton Constructor is private and the client can instantiate a Singleton object

public class Singleton {
 private static Singleton uniqueInstance = null;
 private int data = 0; An instance attribute.
 public static Singleton instance() {
  if(uniqueInstance == null) 
   uniqueInstance = new Singleton();
   return uniqueInstance;
 }
 private Singleton() {}
 // Accessors and mutators here
}


Here's a test program:
public class TestSingleton {
 public static void main(String args[]){
  // Get a reference to the single instance of Singleton.
  Singleton s = Singleton.instance();
  // Set the data value.
  s.setData(34);
  System.out.println("First reference: " + s);
  System.out.println("Singleton data value is: " + s.getData());
  // Get another reference to the Singleton.
  // Is it the same object?
  s = null;
  s = Singleton.instance();
  System.out.println("\nSecond reference: " + s);
  System.out.println("Singleton data value is: " +
  s.getData());
 }
}

And the test program output:
First reference: Singleton@1cc810
Singleton data value is: 34
Second reference: Singleton@1cc810
Singleton data value is: 34