How to implement an interface class using the non-virtual interface idiom in C++?

前端 未结 4 1662
猫巷女王i
猫巷女王i 2020-12-19 15:10

In C++ an interface can be implemented by a class whose methods are pure virtual.

Such a class could be part of a library to describe what methods an object should

4条回答
  •  醉酒成梦
    2020-12-19 15:50

    Commonly, the reason for using the NVI (sometimes also called "Template Method") is that derived classes should only change a part of the base class' behavior. So what you do is this:

    class base {
      public:
        void f()
        {
          // do something derived classes shouldn't interfere with          
          vf();
          // do something derived classes shouldn't interfere with          
          vg();
          // do something derived classes shouldn't interfere with          
          vh();
          // do something derived classes shouldn't interfere with          
        }
      private:
        virtual void vf(); // might be pure virtual, too
        virtual void vg(); // might be pure virtual, too
        virtual void vh(); // might be pure virtual, too
    };
    

    Derived classes can then plug into f() at the spots they are meant to and change aspects of f()'s behavior, without messing up its fundamental algorithm.

提交回复
热议问题