且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在C ++中使用非虚拟接口方法实现接口类?

更新时间:2022-06-06 21:09:24

我认为你有你的NVI模式错误的方式:
http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Non-Virtual_Interface

I think you've got your NVI pattern around the wrong way: http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Non-Virtual_Interface

不确定是否能解决您的问题。

Not sure if that solves your issue though.

class IFoo
{
    public:
       void method() { methodImpl(); }
    private:
       virtual void methodImpl()=0;
};

class FooBase : public IFoo // implement interface IFoo
{
    private:
        virtual void methodImpl();
};

这里有一个例子,为什么你可以使用读取器从XML读取另一个从数据库。注意,公共结构移动到NVI的readFromSource,而非常见的行为移动到私有虚拟getRawDatum。这样,只需要在一个函数中记录日志和错误检查。

Here's an example of why you might do this using a reader that reads from XML and another from DB. Note that common structure is moved into the NVI readFromSource, while non-common behaviour is moved into the private virtual getRawDatum. This way logging and error checking is only needed in the one function.

class IReader
{
  public:
    // NVI
    Datum readFromSource()
    {
       Datum datum = getRawDatum();
       if( ! datum.isValid() ) throw ReaderError("Unable to get valid datum");
       logger::log("Datum Read");
       return datum;
    }
  private:
    // Virtual Bits
    Datum getRawDatum()=0;
};

class DBReader : public IReader
{
  private:
    Datum getRawDatum() { ... }
};

class XmlReader : public IReader
{
   private:
     Datum getRawDatum() { ... }
};