This article describes the C + + Single example mode and its related application methods, share for everyone to reference. The specific methods are analyzed as follows:
Defined:
A class has and has only one instance, and provides a global access point to access it.
Points:
1, the class can only have one instance;
2. This instance must be created by itself;
3. This instance must be provided to the whole system.
Implement one: Single case pattern structure code
The Singleton.h file code is as follows:
#ifndef _singleton_h_
#define _SINGLETON_H_
class SINGLETON
{public
:
static singleton* GetInstance ();
Protected:
Singleton ();
Private:
static Singleton *_instance;
#endif
The Singleton.cpp file code is as follows:
#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;
}
The main.cpp file code is as follows:
#include "singleton.h"
int main ()
{
Singleton *t = Singleton::getinstance ();
T->getinstance ();
return 0;
}
Implementing Two: Printer instances
The Singleton.h file code is as follows:
#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
The Singleton.cpp file code is as follows:
#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::p rintsomething (const char* str2print)
{
cout<< "printer is now working, the sequence:" & lt;<++count<<endl;
cout<<str2print<<endl;
cout<< "done\n" <<endl;
}
The main.cpp file code is as follows:
#include "singleton.h"
int main ()
{
Singleton *t1 = Singleton::getinstance ();
T1->getinstance ();
T1->printsomething ("T1");
Singleton *t2 = Singleton::getinstance ();
T2->printsomething ("T2");
return 0;
}
Makefile File:
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:
$ (CC) $ (CPP.O) cflags-c-o $ <
The effect is as shown in the following illustration:
As you can see, the count for the print order count is continuous and there is only one print device in the system.
I hope this article will help you with the C + + program design.