Item 22. Template Method
The Template Method is not coheed with Templates in C , it is just a design method (or design mode). ------------------------ 1, Template Method designed by Template Method is a method for the base class design, which makes the task of the subclass More clear, the child designer's attention is intended to be in the base class, without having to care about the relationship between the various contract. For the base class, it is "curve to save the country".
2. From the inheritance angle to the member function virtual function, pure virtual function, non-virtual function to virtual function functions, the subclass designer has the right to choose whether Overriding it. Therefore, the base type designer needs to have a default implementation. For pure virtual functions, subclasses must be Overriding it. Non-virtual functions, subclasses can write a non-virtual function (not caled overriding) with the base class, but this function in the subclass cannot be used for polymorphism, so don't write it.
3, from the access rights to the member function private, public, protected ...
4, the realization of Template Method Template Method is achieved by 2, 3 points. The base class uses a public nonvirtual member function to access the protected virtual member function, and subclasses can choose Overriding that protected virtual member function when needed. If it is a Pure Protected Virtual member function, it must be Overriding it.
Class app {public: virtual ~ app (); // ... void startup () {// template method initialize (); if (! validate ()) altinit ();} protected: virtual bool validate () const = 0; virtual void altinit (); // ... private: void initialize (); // ...};
Class myapp: public app {public: // ... private: BOOL VALIDATE () const; void altinit (); // ...};
5. Why do you want to use Template Method? The Template Method makes the base class control the call sequence of the function (execution process), the subclass is only responsible for the implementation of a step (the specific look is empty or pure). This will move the entire system in the case where the subclass does not know the details. It is really very wonderful! MFC is like this. So don't surprise someone to choose "curve to save the country" road.