Singleton pattern : ensures that a class has only one instance and provides a global access point
Singleton has two methods: 1 lazy loading, 2 non-lazy loading
package com.em.singleton; /** * Created by Administrator on 2017/12/23. */ public class Singleton { /* * must be a private constructor * */ private Singleton(){} /** * * non-lazy loading * **/ private static Singleton singleton1 = new Singleton(); public static Singleton getInstance1(){ return singleton1; } /** * lazy loading * * **/ private static volatile Singleton singleton; //volatile guarantees memory visibility in the case of multiple threads public static Singleton getInstance(){ if(singleton ==null){ synchronized (Singleton.class){ //Double lock to prevent simultaneous access by multiple threads if(singleton==null){ singleton = new Singleton(); return singleton; } } } return singleton; } }