Singleton: ensures that a class has only one instance and provides a global access point to it.
UML class diagram:
Implementation Method:
1. Create a static pointer pointing to a unique instance and it is private.
2. Provide a public interface that has obtained the unique instance. If the unique instance does not exist, create it in the interface first.
3. Set the class constructor to private to prevent users from creating instances in other ways.
4. the class destructor is set to private. Because the class has only one instance, you cannot delete it at will. When you call delete to release the instance object, the compiler reports an error indicating that it is invalid.
The basic code for Singleton mode is as follows:
[Cpp]
/*************************************** *****************************
Filename: Singleton. h
Created: 2012-09-24
Author: firehood
Purpose: firehood learning design mode-singleton Mode
**************************************** *****************************/
# Include <stdio. h>
# Pragma once
Class Singleton
{
Public:
Static Singleton * GetInstance (void );
Private:
Static void Destory (void );
Singleton (void );
~ Singleton (void );
Singleton (const Singleton &);
Singleton & operator = (const Singleton &);
Private:
Static Singleton * pInstance;
};
[Cpp]
/*************************************** *****************************
Filename: Singleton. cpp
Created: 2012-09-24
Author: firehood
Purpose: firehood learning design mode-singleton Mode
**************************************** *****************************/
# Include "Singleton. h"
# Include <iostream>
Using namespace std;
Singleton * Singleton: pInstance = NULL;
Singleton: Singleton (void)
{
}
Singleton ::~ Singleton (void)
{
}
Singleton * Singleton: GetInstance (void)
{
If (pInstance = NULL)
{
PInstance = new Singleton ();
// Register the termination function (called when the process exits)
Atexit (Destory );
}
Return pInstance;
}
Void Singleton: Destory (void)
{
If (pInstance)
{
Cout <"Release instance memory..." <endl;
Delete pInstance;
PInstance = NULL;
}
}
Client call code:
[Cpp]
# Include "Singleton. h"
# Include <iostream>
Using namespace std;
Int main (int argc, char * argv [])
{
Cout <"************************************ * "<endl;
Cout <"firehood learning design mode-singleton mode" <endl;
Cout <"************************************ * "<endl;
Singleton * pInstance1 = Singleton: GetInstance ();
Cout <"instance 1:"
Singleton * pInstance2 = Singleton: GetInstance ();
Cout <"instance 2:"
If (pInstance1 = pInstance2)
{
Cout <"instance 1 and instance 2 are the same instance" <endl;
}
System ("pause ");
Return 0;
}
Running result:
*************************************
Firehood learning design mode-singleton Mode
*************************************
Instance 1: 003A64E8
Instance 2: 003A64E8
Instance 1 and instance 2 are the same instance
Press any key to continue...
Release instance memory ..