23 design patterns ----- singleton (singleton)

package demo;
/**
 * Singleton mode (singleton) (also known as lazy mode)
   1. Definition
     This pattern can only produce one object
     Application scenarios: such as: recycle bin of windows, task manager of windows, database connection pool in java, bean management in spring, etc.
  2. Create steps
  1). Make the default constructor private
  2). Define a static property of the type of the current class
  3). Provide a static class method that returns the current static property object
 *
 *
 */
// lazy
public class Singleton {
	 private static class LazyHolder {    
	       private static final Singleton INSTANCE = new Singleton();    
	    }   
     private  Singleton(){};
    public  static  Singleton getInstance(){
    	return LazyHolder.INSTANCE;
 }
}
// hungry man
/*public class Singleton1 {  
    private Singleton1() {}  
    private static final Singleton1 single = new Singleton1();  
    // static factory method   
    public static Singleton1 getInstance() {  
        return single;  
    }  
} */


Guess you like

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