Design pattern learning - singleton pattern

Definition: Ensure that a class has only one instance, and instantiate itself to provide the entire instance to the entire system

scenes to be used:

  1. Environments that require production of unique serial numbers
  2. Requires a shared access point or shared data, such as a program counter, throughout the project
  3. Creating an object consumes too many resources
  4. Environments that need to define a large number of static constants or static methods

Example:

package cn.lonecloud.singleton;

/**
 * @author lonecloud
 * @version v1.0
 * @date 3:44 PM 2018/3/16
 */
public class DemoSingleton {
    
    private static final Demo demo=new Demo();
    public static final Demo getInstance(){
        return demo;
    }
}
class Demo{
}

  

Guess you like

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