先上代碼:
1 package com.test.singleton;
2
3 /**
4 * @author mr.cheng
5 *
6 */
7 public class Singleton {
8 //運用private私有化構造器,其他類不能通過new獲取本對象
9 private Singleton() {
10 }
11 //運用私有靜態instance保存本對象,必須是靜態變量,因為會在getInstance方法中運用
12 private static Singleton instance;
13 //靜態方法是因為不能通過new來獲取對象,只能通過這個靜態方法來獲取對象實例
14 static synchronized Singleton getInstance(){
15 //先判斷保存實例的變量instance是否為空,為空則新建實例,并保存到instance中
16 if(instance == null){
17 //Singleton只有一個構造器,并聲明為private,因此只能在內部調用new 獲取實例
18 instance = new Singleton();
19 return instance;
20 } else{
21 return instance;
22 }
23 }
24 }
25
單列模式主要運用場景:實例化時耗用的資源比較大,或者對象實例比較頻繁,以及要保證在整個程序中,只有一個實例。
例如數據源配置,系統參數配置等。