一. 回调函数的定义为:
函数指针的调用,即是一个通过函数指针调用的函数;
如果你把函数的指针(地址)作为参数传递给另一个函数,当这个指针被用来调用其所指向的函数时,就说这是回调函数。
In computer programming, a callback is any executable code that is passed as an argument to other code, which is expected to call back (execute) the argument at a given time. This execution may be immediate as in a synchronous callback, or it might happen at a later time as in an asynchronous callback.
即:把一段可执行的代码像参数传递那样传给其他代码,而这段代码会在某个时刻被调用执行,就叫做回调。如果代码立即被执行就称为同步回调,如果在之后晚点的某个时间再执行,则称为异步回调。
二.
项目大致结构分析:在linktableInternal.h中定义了链表结构,linktable.h文件中声明了一些链表相关的操作函数,而inktable.c实现了这些方法,而三个实现回调的关键函数利用了这些链表方法
如下为三个关键函数:
tLinkTableNode * SearchLinkTableNode(tLinkTable *pLinkTable, int Condition(tLinkTableNode * pNode, void * args),void * args)
{
if(pLinkTable == NULL || Condition == NULL)
{
return NULL;
}
tLinkTableNode * pNode = pLinkTable->pHead;
while(pNode != NULL)
{
if(Condition(pNode, args) == SUCCESS)
{
return pNode;
}
pNode = pNode->pNext;
}
return NULL;
}
int Condition(tLinkTableNode * pLinkTableNode, void * args)
{
char * cmd = (char*) args;
tDataNode * pNode = (tDataNode *)pLinkTableNode;
if(strcmp(pNode->cmd, cmd) == 0)
{
return SUCCESS;
}
return FAILURE;
}
// Callback function
int SearchCondition(tLinkTableNode * pLinkTableNode, void * args)
{
char * cmd = (char*) args;
tDataNode * pNode = (tDataNode *)pLinkTableNode;
if(strcmp(pNode->cmd, cmd) == 0)
{
return SUCCESS;
}
return FAILURE;
}
函数SearchCondition被当作参数传递给了另一个函数SearchLinkTableNode即为回调函数的具体实现,函数SearchLinkTableNode中会调用函数SearchCondition来检查是否满足回调的要求。
解耦思想是软件设计中非常重要的一种思想,它可以使得代码更加灵活、可维护、可扩展。通过将不同的功能模块解耦,我们可以实现模块之间的独立性,使得一个模块的修改不会影响到其他模块的正常运行。同时,解耦还可以提高代码的可读性和可测试性,从而更好地保证代码的质量和可靠性。SearchLinkTableNode函数只需要SearchCondition函数有固定类型的输入参数和一个int型的返回值就可以了,我们可以在不违反这个原则的情况下传递其他的函数指针,以实现不同的功能,同时不需要改边SearchLinkTableNode函数本身。这就是软件设计中的解耦思想,即通过解耦不同的功能模块,可以实现代码的灵活性、可维护性和可扩展性。