設計模式學習 – 單例模式
- 2019 年 12 月 29 日
- 筆記
學習、梳理設計模式。
單例模式
單例模式分為餓漢模式和懶漢模式。
餓漢模式
- 私有化構造函數
- 創建私有實例
- 提供公開的獲取實例的方法
public class Person { private static Person instance = new Person(); private Person() { } public static Person getInstance() { return instance; } }
懶漢模式
- 私有化構造函數
- 聲明私有實例
- 提供公開的獲取實例的方法(獲取時為空則進行創建)
public class Person { private static Person instace; private Person() { } public static Person getInstance() { if (instace == null) { return new Person(); } return instace; } }
總結
兩種模式都需要先私有化構造函數以禁止直接new操作來創建實例,不然就失去了單例的意義。
餓漢與懶漢在實例化的時間節點上,不同的地方在於一個是類加載時就實例化,一個是到用到時再去實例化,這也是其區別,前者在類加載時慢但獲取時快,後者在類加載時快但獲取時慢。同時,因為懶漢模式是在用到時才去實例化,也是其線程不安全的地方。
這個時候可以用下面的方式來規避
public static Person getInstance() { if (instace == null) { synchronized (Person.class) { if (instace == null) { return new Person(); } } } return instace; }