“This is the 10th day of my participation in the August More Text Challenge. For details, see: August More Text Challenge.”
Singleton pattern
A singleton has one and only one instance object
Key points:
Create – Constructor private
Externally accessible
Static;
Here’s what I wrote myself:
/** * @author Lucas * @create 2021-08-10 15:01 * @description public class Person {private String name; private Integer age; /** * singleton mode; Requires that there be only one instance object in the system; * * 1. Determine whether it is a hunhune or a slacker and create a static private variable * 2. Constructor private * 3. Externally accessing objects, we will return ** / /** * 1 from our own constructed private objects. * private static final Person Instanc=new Peson(); */ private static Person Instance; /** * 2. Private Person (){system.out.println (" need to create an object Person "); } /**3. External access to * public static methods --> Use static storage method area, Public static Person getPerson(){if (Instance==null){Person(Instance==null){Person(Instance==null) person=new Person(); Instance=person; } return Instance; } public static void main(String[] args) {Person person1 = person.getPerson (); Person person2 = Person.getPerson(); System.out.println(person1==person2); }}Copy the code
In this case, multithreading is unsafe; How to optimize
* Public static methods --> Use the static storage method area, * @return */ public static Person getPerson(){// synchronized Person getPerson(){// synchronized Person getPerson() (Instance==null){ Person person=new Person(); Instance=person; } return Instance; }Copy the code
Optimization of 2:
/** * @author Lucas * @create 2021-08-10 15:16 * @description public class Person {private String name; private Integer age; /** * singleton mode; Requires that there be only one instance object in the system; * * 1. Determine whether it is a hunhune or a slacker and create a static private variable * 2. Constructor private * 3. Externally accessing objects, we will return ** / /** * 1 from our own constructed private objects. * private static final Person Instanc=new Peson(); */ private static volatile Person Instance; /** * 2. Constructor private */ Person (){system.out.println (" need to create an object Person "); } /**3. External access to * public static methods --> Use static storage method area, * @return */ public static Person getPerson(){if (Instance==null){ If (Instance==null){Person Person =new Person(); synchronized (Person. Class){Person Person =new Person(); Instance=person; }} } return Instance; } public static void main(String[] args) {Person person1 = person.getPerson (); Person person2 = Person.getPerson(); System.out.println(person1==person2); }}Copy the code
Essentially: For single-column schema:Basically double locking + memory visibility
2.2. Application scenarios of singleton mode:
System information, basic information of environment variables: