Singleton design pattern: One of the simplest design patterns in Java. This type of design pattern is a creation pattern that provides an optimal way to create objects. In the singleton design pattern, a class can only exist one object instance, the class only provides a method to obtain its object instance implementation idea: 1. The class constructor has access set to private, avoiding other class new objects. 2. Call a static method of the class to return an object created inside the class.

A hungrier implementation of the singleton pattern: instantiate the object at the beginning of the class

public class Test1{ Bank bank =Bank.getInstance(); } class Bank {private Bank(){} prvate static Bank instance = new Bank(); Public static getInstance(){return static getInstance(){return static getInstance(); }}Copy the code

A lazy implementation of the singleton pattern: the object is defined and instantiated in a method

public class Test1{ Bank bank =Bank.getInstance(); } class Bank { private Bank(){} prvate static Bank instance = null; public static getInstance(){ if(instance==null){ instance=new Bank() } return instance; }}Copy the code

Without regard to thread safety, hunny objects take too long to load, and lazy objects can delay the creation of objects. Examples of singletons are database connection pools, task managers, and recycle bins.