Patterns. The Singleton pattern. Implementation in Java

The Singleton pattern. Implementation in Java

This topic is a continuation of the following topic:


Contents


Search other websites:




1. The structure of the Singleton pattern. Picture

The general scheme of the Singleton pattern is shown in Figure 1.

 

The structure of the Singleton pattern

Figure 1. The structure of the Singleton pattern

 

2. The structure of the Singleton pattern with reference to the Java-code

In the Java language codes, the implementation features of the Singleton pattern are shown in Figure 2.

The creation of an instance of the class occurs in the Instance() method. You cannot create an instance of the class from the client code using the new operator, since the class constructor is placed in the protected section. The static method Instance() has access to the constructor from the internal code, which creates a single instance of the class. This single instance is returned by the Instance() method. To be able to determine whether a single instance of a class has been created or not, the Instance() method is declared as static (global).

The structure of the Singleton pattern with reference to the Java-code

Figure 2. The structure of the Singleton pattern with reference to the Java-code

 

3. Source code in Java

Below is the text of a program in Java that implements the Singleton pattern shown in Figures 1, 2.

// Implementation of the Singleton pattern in Java
// A class that demonstrates the Singleton pattern
class Singleton {
  private static Singleton _instance=null; // a reference to the instance of the Singleton class
  private int a; // internal data

  // Protected constructor of the class
  protected Singleton() {
    a = 0;
  }

  // A method that returns a single instance of the Singleton class to the client
  public static Singleton Instance() {
    if (_instance==null) {
      _instance = new Singleton(); // create the instance of the Singleton class
      return _instance;
    }
    else
      return null;
  }

  // Methods to access class data
  public void Set(int _a) {
    a = _a;
  }
  public int Get() { return a; }

  // Method for internal data output
  public void Print() {
    System.out.println("A.a = " + a);
  }
}

public class TestSingleton {

  public static void main(String[] args) {
    // Demonstration of using the Singleton pattern
    // 1. Create an instance of the Singleton class using the Instance() method
    Singleton obj1 = Singleton.Instance();
    if (obj1!=null) {
      obj1.Set(233);
      obj1.Print();
    }
    else
      System.out.println("obj1==null");

    // 2. Attempting to create another instance of the Singleton class
    Singleton obj2 = Singleton.Instance();
    if (obj2!=null) {
      obj2.Set(777);
      obj2.Print();
    }
    else
      System.out.println("obj2==null");
  }
}

The result of the program

A.a = 233
obj2==null

 


Related topics