(1)函数指针方式
通过函数指针进行调用,实现者只需将自己定义的函数作为参数传递给调用者即可。
void fun1(int a)
{
cout << a << endl;
}
void fun2(int a)
{
cout << a*a << endl;
}
void caller(void(*f)(int),int a) //调用者提供接口,具体的实现由客户自己实现
{
f(a);
}
int main()
{
int a;
cin >> a;
if (a > 0)
caller(fun1, a);
else
caller(fun2, a);
return 0;
}
(2)Callback方式
按照要求实现一个C++接口,然后把实现的接口设置给对方,对方需要触发事件时调用该接口。
class IDownloadSink
{
public:
virtual void OnDownloadFinished(const char* pURL, bool bOK) = 0;
};
class CMyDownloader
{
public:
CMyDownloader(IDownloadSink* pSink)
:m_pSink(pSink)
{
}
void DownloadFile(const char* pURL)
{
cout << "downloading: " << pURL << "" << endl;
if(m_pSink != NULL)
{
m_pSink->OnDownloadFinished(pURL, true);
}
}
private:
IDownloadSink* m_pSink;
};
class CMyFile: public IDownloadSink
{
public:
void download()
{
CMyDownloader downloader(this);
downloader.DownloadFile("www.baidu.com");
}
virtual void OnDownloadFinished(const char* pURL, bool bOK)
{
cout << "OnDownloadFinished, URL:" << pURL << " status:" << bOK << endl;
}
};