欧美大屁股bbbbxxxx,狼人大香伊蕉国产www亚洲,男ji大巴进入女人的视频小说,男人把ji大巴放进女人免费视频,免费情侣作爱视频

歡迎來到入門教程網(wǎng)!

C語言

當(dāng)前位置:主頁 > 軟件編程 > C語言 >

C++單例模式應(yīng)用實(shí)例

來源:本站原創(chuàng)|時間:2020-01-10|欄目:C語言|點(diǎn)擊: 次

本文實(shí)例講述了C++單例模式及其相關(guān)應(yīng)用方法,分享給大家供大家參考。具體方法分析如下:

定義:

一個類有且僅有一個實(shí)例,并且提供一個訪問它的全局訪問點(diǎn)。
要點(diǎn):
1、類只能有一個實(shí)例;
2、必須自行創(chuàng)建此實(shí)例;
3、必須自行向整個系統(tǒng)提供此實(shí)例。

實(shí)現(xiàn)一:單例模式結(jié)構(gòu)代碼

singleton.h文件代碼如下:

#ifndef _SINGLETON_H_
#define _SINGLETON_H_

class Singleton
{
public:
  static Singleton* GetInstance();
protected:
  Singleton();
private:
  static Singleton *_instance;
};

#endif

singleton.cpp文件代碼如下:

#include "singleton.h"
#include <iostream>
using namespace std;

Singleton* Singleton::_instance = 0;

Singleton::Singleton()
{
  cout<<"create Singleton ..."<<endl;
}

Singleton* Singleton::GetInstance()
{
  if(0 == _instance)
  {
    _instance = new Singleton();
  }
  else
  {
    cout<<"already exist"<<endl;
  }

  return _instance;
}

main.cpp文件代碼如下:

#include "singleton.h"

int main()
{
  Singleton *t = Singleton::GetInstance();
  t->GetInstance();

  return 0;
}

實(shí)現(xiàn)二:打印機(jī)實(shí)例

singleton.h文件代碼如下:

#ifndef _SINGLETON_H_
#define _SINGLETON_H_

class Singleton
{
public:
  static Singleton* GetInstance();
  void printSomething(const char* str2Print);
protected:
  Singleton();
private:
  static Singleton *_instance;
  int count;
};

#endif

singleton.cpp文件代碼如下:

#include "singleton.h"
#include <iostream>

using namespace std;

Singleton* Singleton::_instance = 0;

Singleton::Singleton()
{
  cout<<"create Singleton ..."<<endl;
  count=0;
}

Singleton* Singleton::GetInstance()
{
  if(0 == _instance)
  {
    _instance = new Singleton();
  }
  else
  {
    cout<<"Instance already exist"<<endl;
  }

  return _instance;
}

void Singleton::printSomething(const char* str2Print)
{
  cout<<"printer is now working , the sequence : "<<++count<<endl;
  cout<<str2Print<<endl;
  cout<<"done\n"<<endl;
}

main.cpp文件代碼如下:

#include "singleton.h"

int main()
{
  Singleton *t1 = Singleton::GetInstance();
  t1->GetInstance();
  t1->printSomething("t1");

  Singleton *t2 = Singleton::GetInstance();
  t2->printSomething("t2");
  return 0;
}

Makefile文件:

CC=g++
CFLAGS = -g -O2 -Wall

all:
  make singleton

singleton:singleton.o\
  main.o  
  ${CC} -o singleton main.o singleton.o

clean:
  rm -rf singleton
  rm -f *.o

.cpp.o:
  $(CC) $(CFLAGS) -c -o $*.o $<

運(yùn)行效果如下圖所示:

 

可以看到,對打印順序count的計(jì)數(shù)是連續(xù)的,系統(tǒng)中只有一個打印設(shè)備。

希望本文所述對大家的C++程序設(shè)計(jì)有所幫助。

上一篇:C++設(shè)計(jì)模式之備忘錄模式

欄    目:C語言

下一篇:C++設(shè)計(jì)模式之中介者模式

本文標(biāo)題:C++單例模式應(yīng)用實(shí)例

本文地址:http://mengdiqiu.com.cn/a1/Cyuyan/3292.html

網(wǎng)頁制作CMS教程網(wǎng)絡(luò)編程軟件編程腳本語言數(shù)據(jù)庫服務(wù)器

如果侵犯了您的權(quán)利,請與我們聯(lián)系,我們將在24小時內(nèi)進(jìn)行處理、任何非本站因素導(dǎo)致的法律后果,本站均不負(fù)任何責(zé)任。

聯(lián)系QQ:835971066 | 郵箱:835971066#qq.com(#換成@)

Copyright © 2002-2020 腳本教程網(wǎng) 版權(quán)所有