0

我想在 C++ 中创建一个适配器类,但是我想适应的接口有几个非虚拟方法。我还能使用常规适配器模式吗?

    #include <iostream>
    using namespace std;

    class  NewInterface{
    public:
      int methodA(){ cout << "A\n"; }
      virtual int methodB(){ cout << "B\n"; }
    };

    class OldInterface{
    public:
      int methodC(){ cout << "C\n"; }
      int methodD(){ cout << "D\n"; }
    };

    class Old2NewAdapter: public NewInterface {
    public:
      Old2NewAdapter( OldInterface* a ){ adaptee = a; }
      int methodA(){ return adaptee->methodC(); }
      int methodB(){ return adaptee->methodD(); }
    private:
      OldInterface* adaptee;
    };

    int main( int argc, char** argv )
    {
      NewInterface* NI = new Old2NewAdapter( new OldInterface() );
      NI->methodA();
      NI->methodB();
      return 0;
    }

如果我有这个设置,输出将是“A D”而不是“C D”。

那么如何在不重写 NewInterface 以使所有方法都是虚拟的情况下使 OldInterface 适应 NewInterface 呢?

4

1 回答 1

0

能介绍一下别的班吗?如果可以,那么您可以将使用 a 的函数替换NewInterface为 even NewerInterface

class NewerInterface
{
public:
    int methodA()
    {
        // preconditions
        int const result = doMethodA();
        // postconditions
        return result;
    }

    int methodB()
    {
        // preconditions
        int const result = doMethodB();
        // postconditions
        return result;
    }

private:
    virtual int doMethodA() = 0;
    virtual int doMethodB() = 0;
};

class Old2NewerInterface : public NewerInterface
{
public:
    explicit Old2NewerInterface(OldInterface& x) : old_(&x)

private:
    virtual int doMethodA() { return old_->methodC(); }
    virtual int doMethodB() { return old_->methodD(); }

private:
    OldInterface* old_;
};

class New2NewerInterface : public NewerInterface
{
public:
    explicit New2NewerInterface(NewInterface& x) : new_(&x)

private:
    virtual int doMethodA() { return new_->methodA(); }
    virtual int doMethodB() { return new_->methodB(); }

private:
    NewInterface* new_;
};
于 2013-08-16T09:38:20.233 回答