單例的目的保證該對象只能存在一個,只有應用場景至關多,列如jedisUtils..java
測試代碼以下:測試
/** * @ClassName: SingeTest * @Description: 飽漢式單例 * @author: ck * @date: 2019年2月23日 下午3:37:47 */ public class SingeTest { public static SingeTest singeTest=null;
// 將構造方法私有化,使其只能經過getSingeTestInstance方法實例化 private SingeTest() {} public static SingeTest getSingeTestInstance() { //判斷是否初始化過,初始化過則直接返回對象 if(singeTest==null) { //加鎖 synchronized (SingeTest.class) { //雙重鎖,判斷是否爲空 if(singeTest==null) { singeTest = new SingeTest(); } } } return singeTest; } }
public class MainSinge { public static void main(String[] args) { SingeTest singeTest1 = SingeTest.getSingeTestInstance(); SingeTest singeTest2 = SingeTest.getSingeTestInstance(); System.out.println(singeTest1==singeTest2); } }
測試結果:spa