日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

单列模式(饿汉)

發布時間:2023/11/30 编程问答 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 单列模式(饿汉) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

單例模式案例

  • 目的:為了讓類中只有一個實例,實例不需要自己釋放
  • 將 默認構造 和 拷貝構造 私有化
  • 內部維護一個 對象的指針
  • 私有化唯一指針
  • 對外提供getinstance方法來訪問這個指針
  • 保證類中只能實例化唯一 一個對象
  • 主席案例

    #include<iostream>using namespace std;//創建主席類//需求 單例模式 為了創建類中的對象,并且保證只有一個對像實例class ChairMan{private://1. 構造函數,進行私有化ChairMan(){//cout << "創建國家主席" << endl;}//拷貝構造私有化ChairMan(const ChairMan&c){}public://提供get方法 訪問主席static ChairMan * getInstance(){return singleMan;}private:static ChairMan * singleMan;};ChairMan * ChairMan::singleMan = new ChairMan;void test01(){/*ChairMan c1;ChairMan *c2 = new ChairMan;ChairMan *c3 = new ChairMan;*//*ChairMan * cm= ChairMan::singleMan;ChairMan * cm2 = ChairMan::singleMan;*///ChairMan::singleMan = NULL;ChairMan *cm1= ChairMan::getInstance();ChairMan *cm2 = ChairMan::getInstance();if (cm1 == cm2){cout << "cm1和cm2相同" << endl;}else{cout << "cm1和cm2相同" << endl;}//ChairMan *cm3 = new ChairMan(*cm2);//if (cm3 == cm2)//{// cout << "cm3和cm2相同" << endl;//}//else{// cout << "cm3和cm2相同" << endl;//}}int main(){//cout << "main調用" << endl; 主席先于main調用test01();system("pause");return 0;}

    打印機案例

    #include<iostream>#include<string>using namespace std;class Printer{private://默認構造函數私有化Printer(){ m_Count = 0; };//拷貝構造函數私有化Printer(const Printer& p){};public://對外提供接口訪問唯一一個實例static Printer *getInstance(){return singlePrinter;}//打印功能void printText(string text){cout << text << endl;m_Count++;cout << "打印機使用了次數為:" << m_Count << endl;}private:static Printer *singlePrinter;int m_Count; //打印次數};Printer * Printer::singlePrinter = new Printer;void test01(){//拿到打印機Printer *ptr= Printer::getInstance();ptr->printText("離職報告");ptr->printText("入職報告");ptr->printText("加薪申請");ptr->printText("升級申請");ptr->printText("退休申請");}int main(){test01();system("pause");return 0;}

    總結

    以上是生活随笔為你收集整理的单列模式(饿汉)的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。