Exercise tive C ++ item35: consider other options than virtual functions

Source: Internet
Author: User

1. Alternatives to virtual functions:

  • (1) Use the non-Virtual Interface (nvi) method, which is a special form of the template method design mode. This allows the customer to call a private virtual function indirectly through only non-virtual functions. The Public Non-virtual function is called the "wrapper" of the private virtual function ). Public Non-virtual functions can do some other work before and after calling virtual functions (such as the lock and unlock of mutex, validation constraints, etc ).
  • (2) Replace a virtual function with a "function pointer member variable", which is a form of decomposition in the strategy design pattern.
  • (3) Replace the virtual function with the tr1: function member variable to allow the use of any callable object with a signature that is compatible with the requirement (this expression is too obscure, it is hard to understand, see the example below ). It is also a form of strategy design patterns.
  • (4) replace virtual functions in the inheritance system with virtual functions in another inheritance system. This is a traditional implementation method of the strategy design model.

2. Case study: Calculation of damage values of players in the game.

(1) generally, you can use the following virtual functions:

Class gamecharacter {public: Virtual int healthvalue () const; // returns the physical strength of the character. The derived class can be modified ...};

(2) Use the nvi method to call private virtual functions using a common public function in the base class.

Class gamecharacter {public: int healthvalue () const {// The derived class cannot be redefined... // do some work beforehand int retval = dohealthvalue (); // call the private function for calculation... // do some post-event work return retval ;}... PRIVATE: Virtual int dohealthvalue () const {// The derived class can be redefined... // provide the default algorithm }};

(3) Use function pointers.

Class gamecharacter; // pre-declaration // The following function is the default Algorithm for calculating physical strength values: int defaulthealthcalc (const gamecharacter & GC); Class gamecharacter {public: typedef int (* healthcalcfunc) (const gamecharacter &); explicit gamecharacter (healthcalcfunc HCF = defaulthealthcalc): healthfunc (HCF) {} int healthvalue () const {return healthfunc (* This );}... PRIVATE: healthcalcfunc healthfunc ;};

This method can:

  • <1> by defining different calculation methods for physical strength values, different computation methods can be implemented by calling different functions for the same type of characters.
  • <2> the physical strength calculation method of a person can be changed during running (equivalent to re-assigning a value to the private variable of gamecharacter ).

This method (including the next two methods) may use functions outside the class to reduce encapsulation.

(4) use tr1: function to complete the strategy mode.

Class gamecharacter; int defaulthealthcalc (const gamecharacter & GC); Class gamecharacter {public: // healthcalcfunc can be any "callable ", can be called and accept any things compatible with gamecharacter, and return anything compatible with Int. For details, see: typedef STD: tr1: function <int (const gamecharacter &)> healthcalcfunc; // This definition indicates that healthcalcfunc is a type that accepts a reference of the gamecharacter type and returns an integer. It supports implicit type conversion between explicit it gamecharacter (healthcalcfunc HCF = defaulthealthcalc ): healthfunc (HCF) {} int healthvalue () const {return healthfunc (* This );}... PRIVATE: healthcalcfunc healthfunc ;};

When using this method, p175 introduces three call methods, namely, using three methods to initialize the derived class of gamecharacter: a specific function, a function object, and a class like STD: tr1 :: BIND (& gamelevel: health, currentlevel, _ 1) uses a member function of an object.

Evilbadguy ebg1 (calchealth); // use a function eyecandycharacter ecc1 (heathcalculator (); // use a function object (contains the struct of a function) gamelevel currentlevel; evilbadguy ebg2 (STD:: tr1: BIND (& gamelevel: health, currentlevel, _ 1 ));

(5) Use a typical strategy. The class diagram is as follows:

The specific definitions in the gamecharacter class are as follows:

class GameCharacter{public:explicit GameCharacter(HealthCalcFunc* phcf = &defaultHealthCalc) : pHealthCalc(phcf){}int healthValue() const{return pHealthCalc->calc(*this);}...private:HealthCalcFunc* pHealthCalc;};

3. Strategy Mode: In design patterns, it is defined as: defining a series of algorithms, encapsulating them one by one, and making them replaceable. The Strategy mode allows algorithms to change independently of customers who use it.

The Strategy Mode is based on the following principles:

  • 1) all objects have responsibilities;
  • 2) the specific implementation of these different responsibilities is achieved through the use of polymorphism;
  • 3) Similar algorithms have different implementations and need to be managed.

Note: This is taken from http://blog.csdn.net/wcyoot/article/details/7522152.

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.