In the design pattern of gof, a class is guaranteed to have only one instance and a global access point is provided. Generally, we can make a global variable to make an object accessible, but it cannot prevent you from instantiating multiple objects. The best way is to let the class itself be responsible for saving its unique instance. This class can ensure that no other instance can be created, and it can provide a method to access the instance.
In other words, we often need global objects. For example, in a project, there is only one database access object. In this case, we can consider using the singleton mode. The Singleton mode is better than the global object. The Singleton class can be inherited, as shown in the following example.
The key aspect of the singleton mode is the private and static getinstance of the constructor.
In addition, pay attention to the memory release in C ++. In C ++, Java, and C #, pay attention to the synchronization problem when multithreading occurs.
# Include <iostream. h> Class Csingleton { Public : Static Csingleton * Getinstance (){ If (Null = M_pinstance) m_pinstance =New Csingleton (); Return M_pinstance ;} Static Void Release () // Required. Otherwise, memory leakage may occur. { If (Null! = M_pinstance) {Delete m_pinstance; m_pinstance = NULL ;}} Protected : Csingleton () {cout < " Csingleton " < Endl ;}; Static Csingleton * M_pinstance;}; csingleton * Csingleton: m_pinstance = NULL;