設計模式學習(五):單例模式
阿新 • • 發佈:2018-12-13
2018年08月30日
目錄
1、單例模式概念
- 確保某一個類只有一個例項,並且自行例項化,並且向整個系統提供這個例項。
- 與全域性變數的區別:全域性變數不能實現繼承,而單例模式可以;
2、餓漢模式
package designModel.SingleExampleModel; public class testSingleExample { public testSingleExample() {} private static testSingleExample test = new testSingleExample(); public static testSingleExample getInstance(){ if(test == null){ System.out.println("未例項化。。"); } return test; } public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("1 "+testSingleExample.getInstance()); Thread thread = new Thread(new Runnable(){ @Override public void run() { // TODO Auto-generated method stub for(int i =1; i<11; i++){ System.out.println(i+" "+testSingleExample.getInstance()); } } }); thread.start(); } }
說明:餓漢模式,即物件例項化發生在編譯時,static 靜態變數被初始化了。
console:
1 [email protected] 1 [email protected] 2 [email protected] 3 designModel.Sing[email protected] 4 [email protected] 5 [email protected] 6 [email protected] 7 [email protected] 8 [email protected] 9 [email protected]
10 [email protected]可見上面獲取到的物件都是同一個,單例模式效果。
3、懶漢模式
package designModel.SingleExampleModel; public class testSingleExampleOfLazyType { public testSingleExampleOfLazyType() {} public static testSingleExampleOfLazyType test = null; public static testSingleExampleOfLazyType getInstance(){ if(test == null){ System.out.println("懶漢模式==例項化。。。"); test = new testSingleExampleOfLazyType(); return test; }else { return test; } } public static void main(String [] args){ System.out.println(testSingleExampleOfLazyType.getInstance()); Thread thread = new Thread(new Runnable(){ @Override public void run() { // TODO Auto-generated method stub for(int i = 1;i<11;i++){ System.out.println(i+" "+testSingleExampleOfLazyType.getInstance()); } } }); thread.start(); } }
說明:懶漢模式即,物件的例項化(記憶體分配)發生在被呼叫的那一刻。
懶漢模式==例項化。。。 [email protected]5c2 1 [email protected]5c2 2 [email protected]5c2 3 [email protected]5c2 4 [email protected]5c2 5 [email protected]5c2 6 [email protected]5c2 7 [email protected]5c2 8 [email protected]5c2 9 [email protected]5c2 10 [email protected]5c2
只有當單例模式提供的外部介面被呼叫,物件才發生例項化。