Singleton pattern first

        1. The characteristics of the singleton mode
        1.1 In order to ensure that instances cannot be created and the number of instances cannot be increased, the method of creating instances should be blocked, that is, the constructor is privatized;
        1.2 The instance is statically created in advance in the static area (guarantee There must be an instance);
        1.3 You need to use a member variable to point to this instance. In order to ensure that this instance will always exist and not be modified or deleted, this member variable should be placed in private;
        1.4 Although the member variable has been protected, it is still Need to be accessed by the outside world, read access.
              This member variable is static, and a method to access the variable needs to be provided;
              since this method cannot be called through the object at this time, this method is decorated with static and can be directly accessed through the class name.

        Two, the case of the
singleton mode //single.cpp

#define _CRT_SECURE_NO_WARNINGS

#include <iostream>
#include <string>
using namespace std;

class Printer
{
    
    
public:
	static Printer* getInstance(){
    
    
		return instance;
	}

	void log(string text){
    
    
		cout << "log: " << text<< endl;
	}

private:
	Printer(){
    
    }
	static Printer* instance;
};

Printer *Printer::instance = new Printer;


int main(void)
{
    
    
	Printer *p1 = Printer::getInstance();
	Printer *p2 = Printer::getInstance();

	p1->log("log1");
	p2->log("log2");

	if (p1 == p2)
	{
    
    
		cout << "p1 和p2是一个实例" << endl;
	}

	system("pause");

	return 0;
}

        The effect is as follows:

Figure (1) There is only one instance of the Printer class

Guess you like

Origin blog.csdn.net/sanqima/article/details/105326164