注册回调的作用
在设计模式中注册回调的方式叫做回调模式。在SDK开发中,为增强开发者的SDK通用性,排序或者一些算法逻辑需要使用者进行编写。这时候就需要向SDK传递回调函数。
注册回调的流程
SDK的接口会提供一个注册回调函数,来规范回调函数的格式,如返回值,参数等。
使用者编写一个固定格式的回调函数,来调用SDK提供的注册回调函数。
当然,在c++中注册回调的实现方式是通过函数指针。
栗子
栗子1
这是一个简单的函数调用,假设print()是sdk中的api,我们直接使用时候。
#include<iostream>
#include<cstdio>
using namespace std;
void print(string str);
//----------使用者模块-----------------
int main()
{
print("hello word");
system("pause");
return 0;
}
//----------SDK模块-----------------
void print(string str)
{
printf(str.c_str());
}
栗子2
还是sdk的直接使用,但这次使用函数指针,来间接调用
#include<iostream>
#include<cstdio>
using namespace std;
void print(string str);
//----------使用者模块-----------------
int main()
{
void(*p) (string str);
p = print;
p("hello word");
system("pause");
return 0;
}
//----------SDK模块-----------------
void print(string str)
{
printf(str.c_str());
}
栗子3
这就是一个简单的回调模式。sdk提供注册回调函数,使用者提供回调函数。可以看出,灵活性得到提高。(在前面的栗子中,只能操作printf的操作,在这个栗子中,能进行任何格式相同函数的操作)
#include<iostream>
#include<cstdio>
using namespace std;
typedef void(*P)(string s);//使用函数指针通常先typedef
void print(string str);
void print_test(P p, string);
//----------使用者模块-----------------
int main()
{
print_test(print, "hello word");
system("pause");
return 0;
}
void print(string str)//回调函数
{
printf(str.c_str());
printf("随便写");
}
//----------SDK模块-----------------
void print_test(P p, string str)//注册回调函数
{
p(str);
}