C + + Singleton mode and Singleton class template

Source: Internet
Author: User




1. Single Case mode


(1) Demand: In architecture design, some classes can have at most one object in the entire system life cycle (Single,instance)


(2) Question: How do you define a class so that the class can create at most one object?


To control the number of objects in a class, you must hide the constructor from the external


Ideas:

@1: Sets the Access property of the constructor to private, copies the constructor, and the assignment operator is declared private, preventing the assignment of the object because there can be only one object of this class.

@2: Defines the instance and initializes it to null. Declare a static variable in the class with static type* instance, followed by the access rule for the static adornment, and then the definition is initialized to null outside of the class.

@3: Then in the class to provide a static member function, used to create the object, when we want to create an object, it is necessary to call this function, the function will go inside to access the instance. @4: Accesses the value of instance, when null: Creates an object and marks it with instance (that is, if instance is null, then a new object is created directly to assign the address value to the

instance, let instance mark), and return to this object. Non-null value: Returns the object of the instance tag directly. This ensures that the class can only create one object, which is the singleton pattern. ‘

The object of the singleton pattern is absolutely not needed to be released during the whole system operation, and the system will naturally release this object when the system is finished. Therefore, the singleton pattern object does not need to be in the system runtime, that is, does not need in the system life cycle

Released at the end.

Example: single-case mode


#include <iostream>


using namespace Std;


/*

* Single case mode

*why2016/9/6

*

* The idea of implementing a singleton model:

*

*@1: Sets the Access property of the constructor to private, copies the constructor, the assignment operator is declared private, and prevents the assignment of the object, because the object of this class can only have one.

*@2: Define instance and initialize to null. Declare a static variable in the class with static type* instance, followed by the access rule for the static adornment, and then the definition is initialized to null outside of the class.

*@3: Then in the class to provide a static member function, used to create the object, when we want to create an object, it is necessary to call this function, the function will go to the inside to access the instance.

*@4: Accesses the value of instance, when null: Creates an object and marks it with instance (that is, if instance is null, then a new object is created directly to assign the address to the

*instance, let instance mark), and return to this object. Non-null value: Returns the object of the instance tag directly. This ensures that the class can only create one object, which is the singleton pattern. ‘

*/

/*

* The object of the singleton mode is absolutely not required to be released during the whole system operation, and the system will naturally release this object when the system is finished. Therefore, the Singleton mode object does not need to be in the system running,

* that is, it does not need to be released at the end of the system life cycle.

*/


Class SObject

{

Private

SObject ()//Hide the constructor

{

}

SObject (const sobject&); //Hide copy constructor

sobject& operator = (const sobject&); //Hide Assignment manipulation

Static SObject *c_instance; Declares a pointer to a instance sobject that will be used to mark the object being created and a pointer to that object. Because it is static, it needs to be defined externally, initialized to null

Public

Static sobject* getinstance (); //declaration, used to create an object, because your constructor is already private, so we have to provide one ourselves. Because it is static, it needs to be defined externally.

void print ()

{

cout << ' this = ' << this << Endl;

}

};


sobject* sobject::c_instance = NULL;


sobject* sobject::getinstance ()

{

if (c_instance = = NULL)

{

C_instance = new SObject (); //If the C_instance flag is empty, stating that there is no object creation, create a unique object

}

return c_instance; //Returns a pointer to this created object

}


int main (void)

{

sobject* S1 = sobject::getinstance ();

sobject* s2 = sobject::getinstance ();

S1->print (); //this = 0x893d008

S2->print (); //this = 0x893d008//Description It is true that only one object can be created, because two pointers point to an object

return 0;

}



2, the above code to implement a singleton mode, but is not perfect, such as the need to define static variable c_instance, you must define a static member function getintance (), so we can in perfect.

Solution is: The singleton pattern related code extraction, is the singleton mode of the logical mode of the part, does not affect the other functions of the class, this part of the code out after the development of a singleton class template. When you need a singleton class, use the Singleton class template directly.

Usage is, in the class that needs to use the Singleton class mode, UF meta key friend + class + Singleton class template name < current class name, declare the Singleton class template as the friend of the current class. In the case of a singleton class template, the definition of a static variable is used to

Tag an object, and define a static member function to implement a judgment token to determine whether to create a new object and return the address of the object.


Singleton English is the meaning of singleton mode.


3, good example of using the Singleton mode class:


/************************************************ Single class template program *****************************************/



#ifndef _singleton_h_

#define _singleton_h_


/*

* Single class template

* Implement the logic part of the singleton mode. Other classes later if you want to use the singleton mode can be added to declare this singleton class template as friend, T is to use the template's class name, to implement a singleton mode

*/


Template

< typename T >

Class Singleton

{

Private

Static t* c_instance;

Public

Static t* getinstance ();

};


Template

< typename T >

t* singleton<t>::c_instance = NULL; //Put this tag first to place empty


Template

< typename T >

t* singleton<t>::getinstance ()

{

if (c_instance = = NULL)//See if the class using Singleton mode has already defined the object.

{

C_instance = new T (); //No object defined, create an object//no object defined, create an object

}

return c_instance; ///finally returns a pointer to this object, which records the address of the object. This prevents objects from being defined on this.

}


#endif


/************************************************* class *******************************/for singleton patterns implemented using this singleton class template


#include <iostream>

#include "Singleton.h"


using namespace Std;


/*

*Sobject uses singleton mode, which is implemented using the Add Singleton class template

*

*

*/

At the same time, some functions related to the creation of objects must be made private and hidden. Includes: constructors, copy constructors, assignment operator overloading functions

Class SObject

{

Private

Friend Class singleton<sobject>; //The Singleton class template to be used is declared as a friend of the current class. This allows you to use a singleton class template.

SObject ()

{

}

SObject (const sobject&);

sobject& operator = (const sobject&);

Public

void print ()

{

cout << ' this = ' << this << Endl;

}

};


int main (void)

{

SObject *s1 = Singleton<sobject>::getinstance ();

SObject *s2 = Singleton<sobject>::getinstance ();

SObject *s3 = Singleton<sobject>::getinstance ();

S1->print (); //You will find that the three pointer values are the same, the instructions are all pointing to the same object, indicating the success of the singleton mode, only one object can be created for a class in a singleton mode

S2->print ();

S3->print ();

return 0;

}



C + + Singleton mode and Singleton class template

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.