回调函数与回调函数解耦

一般应用程序直接调用系统、库、底层模块的API;如果反过来,用户写一个函数,让系统直接调用该函数,称为回调。

应用层app.c

#include<stdio.h>
#include"module.h"

void func1(void)
{
    printf("func1...\n");
}
void func2(void)
{
    printf("func2...\n");
}

int main(void)
{
    runcallback(func1);
    runcallback(func2);
    return 0;
}

底层模块module.c

void runcallback(void (*fp)(void))
{
    fp();
}

module.h

#ifndef __RUNCALLBACK__H
#define __RUNCALLBACK__H
void runcallback(void (*fp)(void));
#endif

底层在合适的时机就会去调用应用程序函数。

 

回调函数解耦

高层模块使用回调函数,底层模块在合适的时机就会去调用高层模块的函数,达到模块间双向通信的目的,但同时又引入了耦合。解耦的方法是在两个模块间定义个抽象接口。

app.c

#include <stdio.h>
#include "module.h"

int sd_read(void)
{
    printf("sd read fun\n");
    return 90;
}

struct storage_device sd={
    "sdcard",sd_read
};

void main()
{
    register_device(sd);
    read_dev("sdcard");
}

module.c

#include <stdio.h>
#include "module.h"

#define MAX_DEV  100
struct storage_device dev_list[MAX_DEV]={0};
int num=0;

int register_device(struct storage_device dev)
{
    if(num<MAX_DEV)
        dev_list[num++]=dev;
        return 0;
}

int read_dev(char *dev_name)
{
    int i;
    for(i=0;i<MAX_DEV;i++)
    {
        if(!strcmp(dev_name,dev_list[i].name))
            break;
    }
    if(i==MAX_DEV)
        {
            printf("err\n");
            return -1;
        }
        return dev_list[i].read();
    
}

module.h

#ifndef _MODULE_H_
#define _MODULE_H_

typedef int (*read_fp)(void);
struct storage_device{
    char name[20];
    read_fp read;
};
extern int read_dev(char *dev_name);
extern int register_device(struct storage_device dev);
#endif

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值