Java has 21 kinds of design patterns, which are often asked in the interview is a single case design mode;
The singleton design pattern has two common ways: 1. Lazy: 1) First privatize the constructor so that the class cannot be instantiated, (private class name () {}), 2) Instantiate an empty object in the class itself, (private static class name =null;); 3) construct a method , returns the object of this class, adds a judgment statement in the middle, if the incoming object is a null value, the new one is instantiated, otherwise the object is returned directly;
For example:
/**
* Lazy Type
* @author Chenjun
* 2017-5-2 9:16:05
*/
public class Lazysingleclass {
Private Lazysingleclass () {};
private static Lazysingleclass Lsc=null;
/**
* Synchronous code block prevents multithreading from occurring null pointer exception
* @return
*/
Public synchronized static Lazysingleclass Getlazysingleclass () {
if (lsc==null) {
lsc= new Lazysingleclass ();
}
return LSC;
}
2. A hungry man: similar to the above, write the code directly:
/**
* A hungry man type
* @author Chenjun
* 2017-5-2 8:46:13
*/
public class Singleclass {
Construction method Privatization, cannot be instantiated by new
Private Singleclass () {};
Returns an object of this class
private static final Singleclass s=new Singleclass ();
public static Singleclass getinstance () {
return s;
}
}
Java design pattern--Singleton design pattern