First, we will show an example of the simplest Singleton mode. The Code is as follows:
[Cpp] view plaincopy
Class NetworkService
{
Public:
// A unique method function provided externally, used to obtain a unique object pointer
Static NetworkService * GetInstance ()
{
If (m_pInstance = NULL)
{
M_pInstance = new NetworkService ();
}
Return m_pInstance;
}
Private:
// The constructor is set to private. Other objects cannot be created.
NetworkService ();
Static NetworkService * m_pInstance;
};
// Www.heatperss123.com
This program looks very simple and has almost no problem. Then you can directly use NetworkService: GetInstance () to get the object pointer. However, this program actually implies a question: When should this unique object be released?
One way, We can first implement a method to parse our own resources, then get the object itself through GetInstance (), and call this method to perform the delete operation. This method is feasible, but the implementation method is not good. At least, we should let the program release the resources at the right time, instead of calling the operation by the outside program.
Is there a better way to analyze the object of the Singleton? Yes. You can use static variables to implement this function. As we know, when the program is about to exit, the system will automatically analyze all global or static variables. In addition, static member variables of all classes are automatically destructed. Based on this, we can define such a static member variable in the singleton class. It exists to ensure that when the program exits, clear the unique instance of the singleton class in the destructor. The improved code (refer to other documents) is as follows, defining a static Gargo member:
[Cpp]
Class NetworkService
{
Public:
// A unique method function provided externally, used to obtain a unique object pointer
Static NetworkService * GetInstance ()
{
If (m_pInstance = NULL)
{
M_pInstance = new NetworkService ();
}
Return m_pInstance;
}
Private:
// The constructor is set to private. Other objects cannot be created.
NetworkService ();
Static NetworkService * m_pInstance;
// Implement a private embedded class for releasing object Resources of the NetworkService class
Class Garbo
{
Public:
~ Garbo ()
{
If (NetworkService: m_pInstance)
{
Delete m_pInstance;
}
}
};
// At the end of the program running, the system will call the garbo destructor, a static member of NetService,
// This function will delete the unique instance of the NetService class.
Static Garbo garbo;
};
The Garbo class is defined as a private embedded class of NetworkService to avoid being used elsewhere.