單例模式java
下面是java中使用單例模式的例子c++
下面這個構造函數 是單利的關鍵設計模式
單例模式用c++實現以下圖函數
簡單說就是隻能被new一次,其餘部分要使用業務邏輯層 只能經過將原來的對象複製測試
怎麼複製?spa
這裏的CDALFile是類,pObjFile是類的對象,做爲參數傳到函數init中,在init函數中對單例模式下的對象進行修改設計
這是c++中的單例 ,這是一種設計模式,code
就那業務邏輯層來講, 僅能容許 業務邏輯層對象被實例化一次,簡單說就是隻能被new一次,對象
●單例模式中blog
1 package zzz; 2 3 //單例模式代碼 4 5 public class dd { 6 7 public static int iCount = 0; 8 9 static class abc{ 10 11 public static abc m_a; 12 13 public static abc initabc() 14 15 {//2.自定義函數initabc封裝構造函數abc(),使得構造函數只能在 16 17 //initabc()裏面調用,且經過if語句使得構造函數abc()只能被調用一次 18 19 if (m_a == null) 20 21 { 22 23 m_a = new abc(); 24 25 } 26 27 return m_a; 28 29 } 30 31 private abc()//1.一個無參的空構造函數,且爲private型,保證不爲外部隨意調用 32 33 {} 34 35 /*測試方法:打印m_a的值 36 37 public boolean getM_A(){ 38 39 System.out.println(m_a); 40 41 return true; 42 43 } 44 45 */ 46 47 } 48 49 /** 50 51 * @param args 52 53 */ 54 55 public static void main(String[] args) 56 57 { 58 59 abc.m_a = null;//構造函數是private或protected時,不能用new方法構造出一個對象,是public時能夠 60 61 abc.initabc(); 62 63 64 65 abc test1 = abc.initabc();//調用initabc方法時其實已經跳過abc(),m_a的值是第一次構造時的值 66 67 //test1.getM_A(); 68 69 70 71 abc test2; 72 73 test2 = abc.initabc();//調用initabc方法時其實已經跳過abc(),m_a的值是第一次構造時的值 74 75 //test2.getM_A(); 76 77 System.out.println("nihao"); 78 79 } 80 81 } 82 83