实现适配器设计模式时链接器错误

Linker error while implementing Adapter design pattern

本文关键字:错误 链接 适配器 设计模式 实现      更新时间:2023-10-16

我在下面的代码中得到链接器错误。如果我将ClientInterface的ClientAPI()函数设置为纯虚函数,那么链接器错误就会消失。这种行为的原因是什么?

    // How the interface looks like to the Client
class ClientInterface
{
public:
    virtual void ClientAPI();
    virtual ~ClientInterface(){}
};
template <class TYPE>   //this adaptor class can adapt to any type of legacy application as it is a generic function that uses template parameter to point to any legacy application
class Adaptor : public ClientInterface
{
public:
Adaptor(TYPE *objPtr, void (TYPE:: *fnPtr)())
{
    m_objPtr = objPtr;
    m_fnPtr = fnPtr;
}
void ClientAPI()
{
    /*....
    Do the conversion logic reqd to convert the user params into the params expected by your original legacy application...
    ....*/
    (m_objPtr->*m_fnPtr)(); //Would call the method of the legacy application internally
}
~Adaptor()
{
    if(m_objPtr)
        delete m_objPtr;        
}
private:
TYPE *m_objPtr; //You can keep either pointer to the Legacy implementation or derive the Legacy implementation privately by your Adaptor class
void (TYPE:: *m_fnPtr)();
};
//Adaptee classes below..
class LegacyApp1
{
public:
    void DoThis()
    {
        cout<<"Adaptee1 API"<<endl;
    }
};

//定义了main的执行类,并且包含了" adapter .h"

#include "headers.h"
#include "Adaptor.h"
void Adapter()
{
  ClientInterface **interface_ptr = new ClientInterface *[2];
  interface_ptr[0] = new Adaptor<LegacyApp1>(new LegacyApp1() , &LegacyApp1::DoThis);
  interface_ptr[1] = new Adaptor<LegacyApp2>(new LegacyApp2() , &LegacyApp2::DoThat);
  for(int i = 0; i < 2 ; i++)
  {
    interface_ptr[i]->ClientAPI();
  }
}
int main()
{
  //Testing();
  Adapter();
  char ch;
  cin>>ch;
  return 0; 
}

因此上述代码中的更正如下:只需对原始代码的前几行进行以下更改。

// How the interface looks like to the Client
class ClientInterface
{
public:
//earlier I forgot to define it, so it was giving linker error as  the function is just declared but not defined.
    virtual void ClientAPI(){} 
    virtual ~ClientInterface(){}
};        

谢谢。

相关文章: