Implementation method of inter-class object interaction 3
Different types of objects are often encountered frequently. I will simplify this case here and call Callback model:
A Container object, a Container object, as a container for the Helper object, use the Helper object (called Motor), Helper object to notify the Container object (hereinafter referred to hereinless "Tune"). The interaction between such objects can be much more, here is hereby discussed one-on-one implementation strategy.
Generally used methods are:
Define output interface method
a. By defining the output interface of the Helper class such as: Ihelperev, generally a pure vain class, and put it in a separate header file: IhelpeRev.hstruct Ihelperev {Virtual void Onevent1 () = 0; Virtual void Onevent2 () = 0; ....}; b. Let Container inherit and implement: Container.h # include "IhelpeRev.h" Class Container: Public Ihelperev {Virtual Void Onevent1 () {...} Virtual void Onevent2 () {... } ...};
c. In the Helper class, there is a member pointer of IHELPEREV * M_PIEVENT. The Container object passes this (Dynamic_Cast
Helper.hclass help * m_pievent; public: helper (Ihelperev * pievent): m_pievent (pievent) {...}} void helper ::fireEvent1 () {m_pievent-> onevent1 ();
The advantage of this method is that the method involved in the callback is defined, and it is concluded that a certain scalability has a certain scalability, and the disadvantage is that the dynamic binding mechanism is adopted by most compilers using the C virtual function. Have a certain speed overhead.
2. The forward declaration method is in the Helper class with the Container * m_pevent pointer and defines the definition of the INCLUDE Container class in the Helper class's header file. In the header file of the Container class, the helper * m_phelper pointer is set up (only the pointer can not be helper m_helper, otherwise, compiler is not defined when compiling the Container class), and implements the file part in the CPPP of Container The definition of the include Helper and Container classes, specific reference: Transfer classes (Vol Original) documents between classes.
The advantage of this method is that the address static binding of the callback function can be compiled time type check, which is more convenient to interact based on the source-level class, and the disadvantage is that the members object of the Helper class cannot be set in the Container class, but can only be Member object pointer, you need to dynamically create objects in the Container object.
3. Template Agreement A. Define the Helper class as a template class, type parameter is the type of callback recipient (here Container): Helper.hTemplate
Container.h # include "helper.h" class contact "Helper.h" Class Container {private: helper
This completes the communication connection between interactions, the design of the template Helper
In view of the fact that the author is abandoned, please have to enlighten me.