The singleton pattern ensures that a class has only one instance and provides a global access point to access it.
How to ensure that a class has only one object in memory?
Privatization of construction methods;
Create an object in the class;
Provides access through a public method.
The single model can be divided into two types: hungry type and lazy type.
Starved Han style single case model
Class creates an object as soon as it is loaded.
The Runtime class adopts the starved Chinese style.
public class Child { private String name; private char gender; //Privatization construction method private Child(){ } public void setName(String name){ this.name=name; } public String getName(){ return name; } //Make an object by yourself //Getchildren is a static method. Static methods can only access static variables. so plus static //In order not to let the outside directly access and modify this value, add private private static Child child= new Child(); //Provide public access interface //In order to make the method available to the outside world, add static public static Child getChild(){ return child; } }
public class ChildDemo { public static void main(String[] args){ Child child1= Child.getChild(); Child child2= Child.getChild(); System.out.println(child1);//Child2@1b6d3586 System.out.println(child2);//Child2@1b6d3586 //See if it's the same Kid: Yes System.out.println(child1==child2);//true child1.setName("round"); System.out.println(child1.getName()); } }
Lazy singleton mode
public class Child2 { private String name; private char gender; //Privatization construction method private Child2(){ } //First declared a child private static Child2 child= null; //synchronized: prevent thread safety problems public synchronized static Child2 getChild(){ //Created when in use if(child ==null){ child= new Child2(); } return child; }
public class ChildDemo2 { public static void main(String[] args) { Child2 child1 = Child2.getChild(); Child2 child2 = Child2.getChild(); System.out.println(child1);//Child2@1b6d3586 System.out.println(child2);//Child2@1b6d3586 //See if it's the same Kid: Yes System.out.println(child1 == child2);//true } }