Singleton mode

Time:2021-8-21

Singleton mode

Singleton pattern is one of the simplest design patterns in Java. This type of design pattern is a creation pattern, which provides the best 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 unique object, which can be accessed directly without instantiating the object of this class.

be careful:

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

Problems solved

It can ensure the uniqueness of the object of a class in memory. When the same configuration information object must be used for multiple programs, it is necessary to ensure the uniqueness of the object.

code implementation

Two common implementation methods: hungry man type and lazy man type

Hungry Han style:

public class SingletonTest1
{
    public static void main(String[] args)
    {
        Bank bank1 = Bank.getBank();
        Bank bank2 = Bank.getBank();

        //Verify that the two refer to the same object
        System.out.println(bank1==bank2);
    }
}
class Bank
{
    //1. Privatization constructor
    private Bank()
    {
    }

    //2. Create an object of class internally (note that this object must also be static)
    private static Bank bank = new Bank();

    //3. Provides a public static method that returns the object of the class
    public static Bank getBank()
    {
        return bank;
    }
}

Verification results:

 

 

Lazy:

public class SingletonTest2
{
    public static void main(String[] args)
    {
        Book book1 = Book.getInstance();
        Book book2 = Book.getInstance();

        System.out.println(book1 == book2);
    }
}

class Book
{
    //1. Privatization constructor
    private Book()
    {}
    //2. Declare the current class object and do not initialize it
    private static Book instance = null;

    //3. Declare public static methods
    public static Book getInstance()
    {
        //When an object is needed, judge whether the object exists or not, and create it only when it does not exist
        if (instance == null)
        {
            instance = new Book();
        }

        return instance;
    }
}

Characteristics of the two methods:

Hungry Chinese style is natural and thread safe; Lazy style has the feature of delayed loading (creating objects when used)

Recommended Today

Supervisor

Supervisor [note] Supervisor – H view supervisor command help Supervisorctl – H view supervisorctl command help Supervisorctl help view the action command of supervisorctl Supervisorctl help any action to view the use of this action 1. Introduction Supervisor is a process control system. Generally speaking, it can monitor your process. If the process exits abnormally, […]