I participated in multiple tests and occasionally asked what single-piece mode I would use in my exam. After searching on the internet, I learned that this is a design method in the design mode. The single-piece mode can be used to eliminate global requirements.
Q. What is the single-piece mode?
A. Single-piece mode is A programming method used to ensure that there is only one instance in the entire application, and the resources occupied by this instance are shared throughout the application.
Q how to design an object with only one instance in object-oriented mode?
A. the constructor must be called to generate each object. Restrictions on constructor may meet the requirements. Therefore, the constructor is designed to be private or protected.
Q. How does a private constructor construct an object?
A. declare a static variable of a class. When declaring a variable, you can call a private constructor or construct the object inside a function that has the permission to call a private function (the function in the object has the permission, youyuan has permissions)
After understanding this, let's see how to use the global variable method to build a class that meets the single-piece pattern.
[Cpp]
Class singleton
{
Static singleton s;
Int I;
Singleton (int x): I (x) {}; // The constructors are completely shielded.
Singleton (const singleton &);
Singleton & operator = (singleton &);
Public:
Static singleton & instance () // return object
{
Return s;
}
Int getValue ()
{
Return I;
}
Void setValue (int x)
{
I = x;
}
};
Singleton: s (44); // the object can be initialized here.
Test
[Cpp]
Int main ()
{
Singleton & s = singleton: instance (); // get the object
Cout <s. getValue () <endl;
Singleton & s1 = singleton: instance (); // get the object
S1.setValue (20 );
Cout <s. getValue () <endl;
Return 0;
}
Is this design very beautiful? There are even more beautiful ones. Let's try to get rid of the separate initialization of the sentence.
We know that a local static variable will be initialized once and will be generated only when the function is called. This variable has existed since it was generated. This can meet your needs.
The design is as follows:
[Cpp]
Class singleton
{
Int I;
Singleton (int x): I (x ){};
Singleton (const singleton &);
Singleton & operator = (singleton &);
Public:
Static singleton & instance ()
{
Static singleton s (44 );
Return s;
}
Int getValue ()
{
Return I;
}
Void setValue (int x)
{
I = x;
}
};
Test
[Cpp]
Int main ()
{
Singleton & s = singleton: instance (); // get the object
Cout <s. getValue () <endl;
Singleton & s1 = singleton: instance (); // get the object
S1.setValue (20 );
Cout <s. getValue () <endl;
Return 0;
}
The above method does not limit creating only one object. The above technology supports creating an object pool with limited objects. Consider constructing a static object array. Solve the problem.