A detailed explanation of the singleton design pattern. . . . . . . . . . .

 

public class Demo01 {

public static void main(String[] args) {
// TODO Auto-generated method stub
/* Singleton design pattern: Ensure that the class has only one object in memory.
How to ensure that a class has only one object in memory?
(1) Control the creation of classes, and do not allow other classes to create objects of this class. private
(2) Define an object of this class in this class. Singleton s;
(3) Provide public access. public static Singleton getInstance(){return s}

There are three ways to write singletons:
(1) This way is used for hungry Chinese development.
(2) Lazy-style interviews are written in this way. Multithreading problem?
(3) The third format */

System.out.println(System.in);
System.out.println(System.in);
System.out.println(System.in);

Singleton s1 = Singleton.s;
Singleton s2 = Singleton.s;
Singleton s3 = Singleton.s;
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}
}

class Singleton{
//Create an object
public static Singleton s = new Singleton();

private Singleton(){}

}

//(2) Lazy-style interviews are written in this way. Create an object when it is
needed/*class Singleton{
//Create an object
private static Singleton s = null;

private Singleton(){}

//Instance instance, object
public static Singleton getInstance(){
if(s == null){
s = new Singleton();
}
return s;
}
}*/

//(1) Hungry Chinese-style development is used in this way.
/*class Singleton{
//Create an object
private static Singleton s = new Singleton();

private Singleton(){}

//Instance instance, object
public static Singleton getInstance(){
return s;
}
}*/

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325052698&siteId=291194637