<> Singleton mode :

First in Java Zhongyou 23 Design patterns :

* Create mode : Factory method model , Abstract factory pattern , Singleton mode , Builder pattern , Prototype mode
* Structural mode : Adapter mode , Decorator mode , proxy pattern , Appearance mode , Bridging mode , Combination mode , Sharing mode
* Behavioral model :: Strategy mode , Template method mode , Observer mode , Iterative sub pattern , Responsibility chain model , Command mode , Memo mode , State mode , Visitor mode , Intermediary model , Interpreter mode .
<>1, What is singleton mode :

definition :

A class has only one instance , And this class can create a pattern of this instance by itself . It can avoid the waste of memory resources caused by opening multiple task manager windows , Or there are errors such as inconsistent display contents of each window . For example, can our computer only open one task manager ? Right , This is to prevent waste of resources and other mistakes .

In a project, you can generally obtain the same object through the singleton pattern to call tool methods , This benefit is to save memory resources , I don't have to create multiple different objects , Because this consumes memory resources

In short : A singleton is a program with only one instance , This class is responsible for creating its own objects , Also make sure that only one object is created

Characteristics of singleton mode :

* Constructor private
* Hold properties of your own type
* Provide static methods for obtaining instances externally
Structure diagram of singleton mode :

<>2, Advantages and disadvantages of singleton mode :

advantage :

* Reduced memory overhead
* Avoid multiple occupation of resources
* Set global access point , You can optimize and share access to resources
shortcoming ( Reference from the Internet ):

* Generally, there is no interface , Expansion difficulty . If you want to expand , In addition to modifying the original code , There is no second way , Violation of opening and closing principle
* In concurrent testing , Singleton mode is not conducive to code debugging . During commissioning , If the code in the singleton is not completed , Nor can it simulate the generation of a new object
* The function code of singleton mode is usually written in a class , If the functional design is unreasonable , It is easy to violate the principle of single responsibility
Look at a mind map of single example mode :

<>3, Lazy mode ( More commonly used )

Lazy mode is characterized by delayed initialization , The object is instantiated only when the method is called to obtain the instance
Thread unsafe , Strictly speaking, it is not a singleton mode , The advantage is that the object is created only after obtaining the instance, so it saves more memory overhead

Demo:
public class SingLeton { //1, Has its own type of attribute private static SingLeton instance;
//2, Constructor privatization private SingLeton(){} //3, Provide static methods for obtaining instances externally public static SingLeton
getInstance(){ if (instance == null){ instance = new SingLeton(); } return
instance; } }
Test class :
public class Test { public static void main(String[] args) { // Determine whether the same object is generated
SingLeton s1= SingLeton.getInstance(); SingLeton s2 = SingLeton.getInstance();
System.out.println(s1 == s2); } }
output :
true
<> be careful :

About lazy mode thread unsafe

It is now known that lazy mode threads are unsafe , Then you need to use a lock (synchronized ) To synchronize :
/** * ensure instance Synchronize in all threads */ public class SingLeton2 { //1, The type has its own properties private
static volatile SingLeton2 instance ; //2, Constructor privatization private SingLeton2() { } public
static synchronized SingLeton2 getInstance() { //getInstance Method plus synchronization if (instance
== null) { instance = new SingLeton2(); } return instance; } }
If it is write multithreading , Do not delete the keyword in the above example code volatile and synchronized, Otherwise, there will be thread unsafe problems . If you don't delete these two keywords, you can
Ensure thread safety , But sync every time you visit , Will affect performance , And consume more resources , This is the disadvantage of lazy singleton .

<>4, Hungry man model 【 Recommended use 】

Hungry man mode thread safety , Commonly used , However, it is easy to generate garbage objects , Because the hungry man mode is initialized as soon as the class is loaded
Examples are given

Demo:
/** * * Hungry man model */ public class SingLeton { // Hold properties of your own type ( Like a lazy man )
// because static modification , It is executed only once when the class is loaded , Instantiate the object when the class is loaded private static SingLeton instance = new
SingLeton(); // Constructor privatization , Object cannot be created through it private SingLeton(){}; // Provide static methods for obtaining instances externally public
static SingLeton getInstance(){ return instance; } }
Test class :
public class Test { public static void main(String[] args) { // Determine whether the same object is generated
SingLeton s1= SingLeton.getInstance(); SingLeton s2 = SingLeton.getInstance();
System.out.println(s1 == s2); } }
output :
true
Comparison between lazy man mode and hungry man mode :

* Lazy mode delayed loading , Non thread safe , Hungry man mode thread safety
* Lazy mode just runs without instantiating objects , Instantiate the object when necessary , It is equivalent to saving memory cost
* As long as the hungry man mode runs, it will be initialized when the class is loaded , You need to use more memory
graphic :

<>5, Application scenario of singleton mode :

* Some classes that need to be created frequently , Using singleton can reduce the memory pressure of the system
* When this class requires only one object to be generated , Like everyone's name
* Class takes more resources when creating an instance , Or the instantiation takes a long time , And often used
* Objects that frequently access databases or files
* Classes need to be instantiated frequently , When the created objects are frequently destroyed , Such as multithreaded thread pool
<>6, Application examples of singleton mode

Here, the lazy singleton mode is used to simulate the generation of the class monitor
analysis : In each semester , There is only one monitor in the class , Therefore, it is suitable to implement in singleton mode

Person class :
/** * Use lazy mode */ public class Person { // ensure instance Synchronize in all threads private static
volatile Person instance; private Person(){ System.out.println(" Produce a monitor "); }
// add synchronized lock public static synchronized Person getInstance(){ if(instance
== null){ instance = new Person(); }else { System.out.println(
" error message : There is already a monitor , No more "); } return instance; } public void getName(){ System.out.
println(" I'm the monitor : cockroach "); } }
Test class :
public class Test { public static void main(String[] args) { Person p1 = Person
.getInstance(); p1.getName(); // Output monitor name Person p2 = Person.getInstance(); p2.
getName(); if(p1 == p2){ System.out.println(" The two squad leaders are the same person "); }else { System.out.
println(" The two squad leaders are the same person "); } } }
Operation results :
Produce a monitor I'm the monitor : cockroach error message : There is already a monitor , Can no longer produce I'm the monitor : cockroach The two squad leaders are the same person
Summary :

This is the singleton mode , When the program has generated an object , A new object will not be generated , Even if there are multiple objects, it is the same object , When using lazy mode, you need to pay attention to thread safety , It is more recommended to use the hungry man mode at ordinary times , Attention should also be paid to the occupation of resources .

Technology