一、概述
1、簡介
所謂單例模式指的是一個類只允許產生一個實例化的對象;
2、分類
懶漢式、飽漢式;
二、詳解
1、餓漢式
簡介:
構造方法私有化,外部無法產生新的實例化對象,只能通過static方法取得實例化對象;
代碼示例:
package com.zibo.design_mode.singleton;
public class SingletonHunger {
/**
* 在類的內部可以訪問私有結構,所以可以在類的內部產生實例化對象
*/
private static SingletonHunger instance = new SingletonHunger();
/**
* private 聲明構造,不能直接通過new的方式進行創建
*/
private SingletonHunger() {
}
/**
* 返回對象實例
*/
public static SingletonHunger getInstance() {
return instance;
}
public void print() {
System.out.println("餓漢式單例模式!");
}
}
2、懶漢式
簡介:
當第一次去使用Singleton對象的時候纔會爲其產生實例化對象的操作;
代碼示例:
package com.zibo.design_mode.singleton;
public class SingletonLazy {
/**
* 聲明變量
*/
private static volatile SingletonLazy singleton = null;
/**
* 私有構造方法
*/
private SingletonLazy() {
}
/**
* 提供對外方法
* @return 實例對象
*/
public static SingletonLazy getInstance() {
// 還未實例化
if (singleton == null) {
synchronized (SingletonLazy.class) {
if (singleton == null) {
singleton = new SingletonLazy();
}
}
}
return singleton;
}
public void print() {
System.out.println("懶漢式單例模式!");
}
}
3、說明
當多個線程併發執行 getInstance 方法時,懶漢式會存在線程安全問題,所以用到了 synchronized 來實現線程的同步,當一個線程獲得鎖的時候其他線程就只能在外等待其執行完畢。而餓漢式則不存在線程安全的問題。