Linux:C语言实现面向接口编程
面向接口编程不是什么新鲜玩意,说得直白点就是函数指针的使用,不过我觉得可以形成一种编程的思想来指导嵌入式程序设计,特别是对于降低代码的耦合还是比较奏效的。
代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int start(void * p);//接口函数,乙方实现具体的逻辑
int working(void * p);//接口函数,乙方实现具体的逻辑
int befree(void * p);//接口函数,乙方实现具体的逻辑
struct ApiFunc * initial (void * p,void * a, void * b, void * c, char * s); //初始化函数,甲方调用传入参数
//面向接口编程,先定义出接口
struct interface
{//包含三个接口函数
int (* start)(void );
int ( working)(void );
int ( befree)(void *);
};
//再定义出一个结构体用来传递参数
struct ApiFunc
{
struct interface inter1;
char name[20];
int a;
int b;
int c;
};
struct ApiFunc * initial(void * p,void * a, void * b, void * c, char * s)//初始化函数,接收甲方调用的参数并初始函数指针
{
struct ApiFunc *Ap = (struct ApiFunc *)p;
Ap->a = *(int *)a;
Ap->b = *(int *)b;
Ap->c = *(int *)c;
strcpy(Ap->name,s);
printf(“%s\n”,Ap->name);
Ap->inter1.start = start;
Ap->inter1.working = working;
Ap->inter1.befree = befree;
return Ap;
}
int start(void * p)
{
struct ApiFunc *Ap = (struct ApiFunc *)p;
printf("%d:%s %s\n",Ap->a,Ap->name,"start work");
return 0;
}
int working(void * p)
{
struct ApiFunc *Ap = (struct ApiFunc *)p;
printf(“%d:%s %s\n”,Ap->b,Ap->name,“is working”);
return 0;
}
int befree(void * p)
{
struct ApiFunc *Ap = (struct ApiFunc *)p;
printf(“%d:%s %s\n”,Ap->c,Ap->name,“is free!”);
return 0;
}
int main(int argc, const char * agrv[])
{
int a = 1;
int b = 2;
int c = 3;
char buf [20] = {“I am a worker”};
struct ApiFunc myapi;
struct ApiFunc * p = initial(&myapi,(void *)&a,(void *)&b,(void *)&c,buf);//调用initial函数初始化ApiFunc结构体
myapi.inter1.start§;
myapi.inter1.working§;
myapi.inter1.befree§;
}