ArticleDirectory
- Problem
- Mode Selection
- Implementation
I personally think that the singleton mode is the simplest, most common, and easiest to implement in the design mode, and also the mode that should be most familiar with and mastered. Not to mention the singleton model, which is the most widely used way for companies to learn about and grasp the design when they are recruiting. It is very common to solve the singleton mode. How do we create a unique variable (object )? In the object-based design, we can create a global variable (object) to implement it. In the design paradigm (such as C ++) that combines object-oriented and process-oriented, we can also implement this through a global variable. However, when we encounter a pure object-oriented paradigm, this can only be achieved through the singleton model, maybe this is why many companies often examine the singleton mode when recruiting Java developers. The Singleton mode is very useful in development. The specific usage is described in the discussion. The typical structure of Singleton mode is as follows: In the structure diagram of Singleton mode, we can see that we maintain a static member variable to record this unique object instance. Obtain this unique instance by providing a staitc interface instance. Implementation // Singleton. h
#
Ifndef _ Singleton_h _
#
Define _ Singleton_h _
#
Include < Iostream >
Using
Namespace STD;
Class Singleton
{
Public :
Static Singleton * Instance ();
Protected :
Singleton ();
Private :
Static Singleton * _ Instance;
};
#
Endif //~ _ Singleton_h _ // Singleton. cpp
#
Include "Singleton. H"
#
Include < Iostream >
Using
Namespace STD;
Singleton * Singleton : : _ Instance = 0 ;
Singleton : : Singleton ()
{
Cout < "Singleton ...." < Endl;
}
Singleton * Singleton : : Instance ()
{
If (_ Instance = 0 )
{
_ Instance =
New Singleton ();
}
Return _ Instance;
} // Main. cpp
#
Include "Singleton. H"
#
Include < Iostream >
Using
Namespace STD;
Int Main ()
{
Singleton * Psingleton = Singleton : : Instance ();
Return 0 ;
} Singleton ....
Press any key to continue... from Weizhi note (wiz)