Dynamic Class (class factory) Summary

Source: Internet
Author: User

Dynamic Class (class factory) Summary

I. The role of dynamic classes

A similar example of a dynamic class application is the Create method of the CWnd class in MFC, whose first parameter is the name of the window class, which allows the user to create the corresponding window through the name of the class. C + + is not a dynamic language, so it is not possible to implement dynamic creation of classes from a language mechanism, but it is obvious that such requirements exist.

To do this, you must have a central administration that registers the name of the class and can call a method by name to create the appropriate class. Combining the design ideas of a class factory, here we have a set of base classes in the inheritance system as the "Central Administration," which maintains the necessary information for all derived classes, including the class name and the factory function, which must establish a mapping relationship, and map is a good choice.

Second, dynamic class principle

1. Basic Principles

A dynamic class is a static map defined for a base class, as in the following example:

Static Map<const char*, classgen> class_set;

Thus, none of the newly created classes can be recorded in this map table, and it is also easy for the program to invoke the response class by name.

The rest of the work is done around this map, and it's all about adding and finding maps.

With macro definitions, you can speed up your program's responsiveness.

The implementation of dynamic classes, code is not unique, function is not limited to this. However, the following implementation of the simple dynamic class will give us a lot of reference value.

2, macro definition of the small knowledge

There is "\" at the end of each line in the code to interpret the newline symbol at the end of the line to avoid affecting the macro definition. The "# #" symbol acts as a connection in the macro definition, such as

#define FUN (Var) var# #ing

The result of the last Fun (str) is string.

The value of the variable represented by "#" in the macro definition, such as

#define FUN (Var) #var

String str = fun (string);

The value of STR is "string", and if there is no #, then the translated statement is a string str = string which will cause an error.

3. Source Code Analysis

In the dynamic class creation process, you only need to use the following four statements:

Declare_dyncrt_base (Base)//Declare Dynamic base class
Declare_dyncrt_class (Derived, Base)//Declare dynamic class

Implement_dyncrt_base (Base)//implement Dynamic base class
Implement_dyncrt_class (Derived)//Implementing Dynamic Classes
The next two implementations, which are two variable definitions, mainly say the first two statements, can be summed up in one statement in the following code:

Base::register (#derived, Create); \

This statement is in a dynamically derived class, which means to invoke the Register function of the dynamic base class, the first #derived is the class name of the dynamically derived class, and create is a pointer to the dynamic base class type that is called by the dynamic derived class's own creation function, which actually points to the derived class.

Because it is a macro definition, these operations are already done before the main function is run.

In addition, the process of compiling the program is as follows:

C Source Program header file--pre-compile processing (CPP)--the compiler itself----optimizer----assembler----Link to the executable file

Third, dynamic class source code analysis

#ifdef _msc_ver#pragma Warning (disable:4786) #endif # include <iostream> #include <map>using namespace std;/     /used to declare a base class with dynamic creation #define DECLARE_DYNCRT_BASE (base) public:typedef base* (*classgen) (); static void Register (const char* class_name, Classgen class_gen) {Class_set.insert (Map<const char*, CLASSG     En>::value_type (Class_name, Class_gen));         } public:static base* Create (const char* class_name) {map<const char*, classgen>::iterator iter;         if (iter = Class_set.find (class_name)) = Class_set.end ()) {return ((*iter). second) ();     } return NULL; } protected:static map<const char*, classgen> class_set; Used to implement the base class #define Implement_dyncrt_base (Base) map<const char*, base::classgen> base::class_set;// Used to declare a class that can be dynamically created #define DECLARE_DYNCRT_CLASS (derived, base) public:struct derived# #Register {derived# #Re Gister () {static bool BregistEred = false;                 if (!bregistered) {base::register (#derived, Create);             Bregistered = true;     }         }     };     Static base* Create () {return new derived; }//is used to implement a class that can be dynamically created #define IMPLEMENT_DYNCRT_CLASS (derived) static derived::d erived# #Register derived# #_for_ registering; Test class base{Declare_dyncrt_base (Base)//Declare Dynamic base class Declare_dyncrt_class (base, Base)//base class You can also dynamically create public:vir    tual void Print () {cout << "This is Base" << Endl; }};implement_dyncrt_base (Base)//implement Dynamic base class Implement_dyncrt_class (base)//Implement Dynamic classes class Derived:public base{Declare_dync Rt_class (Derived, Base)//Declare dynamic class public:virtual void Print () {cout << "This is Derived" << end    L }};implement_dyncrt_class (Derived)//Implement dynamic class int main () {base* pbase = base::create ("Base");//class name can be dynamically entered if (PBase) pBa Se->print (); Create successful call virtual function else cout << "Create Base ErroR "<< Endl; base* pderived = base::create ("Derived"); The class name can be dynamically entered if (pderived) pderived->print ();        Create successful call virtual function else cout << "Create Derived error" << Endl;    System ("pause"); return 0;}

  

Dynamic Class (class factory) Summary

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.