Purpose: ensure that a class has only one instance and provides a global access point to it.
Applicability:
When a class does not know the class of the object it must create.
When a class wants its subclass to specify the object it creates.
Structure:
Implementation:
1) Ensure a unique instance
Singleton mode is a simple example implemented in C ++. An operating system running on a computer is considered to be a unique instance of the COSSingleton class. When the system is started, only one operating system is created. To do this, you only need to declare a class operation (that is, a static member function) in the COSSingleton class to ensure that only one instance is created.
Class COSSingleton
{
Public:
Static COSSingleton * Instance ();
Virtual void ShowOSVersion ();
Protected:
COSSingleton (void );
Private:
Static COSSingleton * _ instance;
};
It contains a pointer to its unique instance. Note that the access control of the constructor is protected. This is for the purpose of scalability (subclass inheritance), without breaking the Singleton pattern, you cannot create multiple instances. The implementation is as follows:
Code COSSingleton * COSSingleton: _ instance = NULL;
Void COSSingleton: ShowOSVersion ()
{
Std: cout <"Unknow ";
}
COSSingleton * COSSingleton: Instance ()
{
If (_ instance = NULL)
{
_ Instance = new COSSingleton ();
}
Return _ instance;
}
2) create a subclass of the Singleton class
Now let's imagine that multiple systems are installed on one computer, and you will be prompted to select the system to enter when starting. In fact, the problem is converted to which subclass of Singleton is used to instantiate the operating system to be started. Select the parameter subclass type. The code for restructuring the Instance () function is as follows:
Code Static COSSingleton * Instance (int index );
COSSingleton * COSSingleton: Instance (int index)
{
If (index = 0)
{
Return new CWinOS ();
}
Else if (1 = index)
{
Return new CLinuxOS ();
}
Else
{
If (_ instance = NULL)
{
_ Instance = new COSSingleton ();
}
Return _ instance;
}
}
In this way, object creation is delayed to subclass, and uniqueness is ensured. Of course, this implementation will be overwhelmed as the number of child classes increases, and the Instance () function must be modified each time. The solution is to use the registry. Store or register subclass information in advance. In the Instance function, only search for and return the corresponding subclass Instance object.