23 Design Patterns --------- Singleton Pattern

1. Introduction to Singleton Pattern

The Singleton Pattern is one of the simplest design patterns in Java. This type of design pattern is a creational pattern, which provides an optimal way to create objects.

This pattern involves a single class that is responsible for creating its own objects while ensuring that only a single object is created. This class provides a way to access its only object, directly, without instantiating an object of the class.


1. A singleton class can only have one instance.
2. A singleton class must create its own unique instance by itself.
3. The singleton class must provide this instance to all other objects.

The singleton pattern definition in Java: "A class has one and only one instance, and instantiates itself to provide the entire system."

2. Introduction to the singleton pattern

Intent: To ensure that there is only one instance of a class, and to provide a global access point to it.

The main solution: a globally used class is frequently created and destroyed.

When to use: When you want to control the number of instances and save system resources.

How to solve: Determine whether the system already has this singleton, if so, return it, if not, create it.

Key code: The constructor is private.


1. There is only one teacher in a class.
2. Windows is multi-process and multi-threaded. When operating a file, it is inevitable that multiple processes or threads operate a file at the same time, so the processing of all files must be carried out through a unique instance.
3. Some device managers are often designed as a singleton mode. For example, a computer has two printers. When outputting, it is necessary to process that the two printers cannot print the same file.

1. There is only one instance in the memory, which reduces the memory overhead, especially the frequent creation and destruction of instances (such as the home page cache of the School of Management).
2. Avoid multiple occupation of resources (such as file writing operations).
Disadvantages: No interface, no inheritance, conflicts with the principle of single responsibility, a class should only care about the internal logic, not how to instantiate it outside.

scenes to be used:

1. It is required to produce a unique serial number.
2. The counter in the WEB does not need to be added to the database every time it is refreshed, but is cached first with a singleton.
3. An object created needs to consume too many resources, such as the connection between I/O and the database.

Note: The synchronization lock synchronized (Singleton.class) needs to be used in the getInstance() method to prevent multiple threads from entering at the same time and causing instance to be instantiated multiple times.

3.0 Singleton mode implements DEMO

We will create a SingleObject class. The SingleObject class has its private constructor and a static instance of itself.

The SingleObject class provides a static method for the outside world to obtain its static instance. The SingletonPatternDemo class uses the SingleObject class to get the SingleObject object.

step 1
Create a Singleton class.

public class SingleObject {
   //Create an object of SingleObject
   private static SingleObject instance = new SingleObject();
   //Make the constructor private so the class won't be instantiated
   private SingleObject(){}
   //Get the only available object
   public static SingleObject getInstance(){
      return instance;
   public void showMessage(){
      System.out.println("Hello World!");

Step 2
Get a unique object from the singleton class.

public class SingletonPatternDemo {
   public static void main(String[] args) {
      //invalid constructor
      //Compile-time error: Constructor SingleObject() is invisible
      //SingleObject object = new SingleObject();
      //Get the only available object
      SingleObject object = SingleObject.getInstance();
      //show message

Step 3
Execute the program and output the result:

Hello World!

4.0 Several implementations of the singleton pattern

There are several ways to implement the singleton pattern, as follows:

4.1 Hungry Chinese style

Whether to initialize Lazy: No

Is it multi-thread safe: yes

Difficulty to achieve: easy

Description: This method is more commonly used, but it is easy to generate garbage objects.
Advantages: There is no lock, and the execution efficiency will be improved.
Disadvantages: The class is initialized when the class is loaded, which wastes memory.

Hungry-style has created a static object for the system to use at the same time as the class is created, and will not be changed (final) in the future, so it is inherently thread-safe.

Hungry Chinese may be a waste of memory (if you don't understand, please point out)

code show as below:

//Hungry singleton
public class Hungry {

    //Hungry will load all the objects as soon as they come up, but if they are not used here, it will lead to a waste of space.
    private byte[] data = new byte[1024 * 1024];
    private byte[] data1 = new byte[1024 * 1024];
    private byte[] data2 = new byte[1024 * 1024];
    private byte[] data3 = new byte[1024 * 1024];

    //private no-argument constructor
    private Hungry() {


    //Hungry Chinese style creates a unique immutable object as soon as it comes up (it will load his object regardless of 3721)
    private final static Hungry HUNGRY = new Hungry();

    //throw an external method
    public static Hungry getInstance() {
        return HUNGRY;


4.2 The Lazy Man

To be continued; it's too late to go to bed

Tags: Java Design Pattern Singleton pattern

Posted by AndrewJ1313 on Thu, 01 Sep 2022 04:27:53 +0930