Singleton design pattern:

Design patterns: Design patterns are optimized code structures, programming styles, and ways of thinking about problem solving after summarizing and theorizing in a large number of practices.

There are 23 common design patterns: singleton design pattern, factory design pattern, agent design pattern, observer design pattern, decorative design pattern……

Singleton design pattern: Only one object of a class can be created throughout the project.

How to do it: lazy vs. hungry

The difference between slacker and hungry

Lazy: 1. Threads are not safe. 2. Delay the creation of the object, to a certain extent, save the memory overhead (lazy loading). Hungry: 1. Threads are safeCopy the code

The hungry type:

Private Bank(){} //2. Private static Bank Bank =new Bank(); Public static Bank getInstance(){return Bank; }}Copy the code

LanHanShi:

Class Computer1{//1. Private Computer1(){} //2. Provides a declaration for an object of that class. Private Static Computer1 Computer1 =null; Public static Computer1 getInstance(){//4. Create an object if(computer1==null){computer1=new computer1 (); } return computer1; } } public class SingletonTest { public static void main(String[] args) { System.out.println(Bank.getInstance()); System.out.println(Bank.getInstance()); System.out.println(Bank.getInstance()); System.out.println(Bank.getInstance()); }}Copy the code