一、介绍
适配器模式(Adapter Pattern)是作为多个不兼容的模块之间的桥梁。它结合了多个模块的功能。因C语言没有类和继承等特性,所以本文只讨论接口适配器,至于类适配器和对象适配器不在本文讨论范围。例如,在需要解码的程序中,一个上位机(用户)需要跟解码器通信,但是解码器需要能解码不同通信协议的数据包。
二、工作原理
- 将一个模块的接口转换成另一种接口,转换后的接口可以兼容。
- 调用者(用户)不需要知道各模块内部的实现,方便增减模块,可以解耦,方便移植
三、适配器图解
四、代码示例
common.h
#define ADAPTER_PARAMS Protocol,param1 param2 param3 prarm4
typedef struct ProtocolStruct *Protocol;
typedef struct ProtocolInterfaceStruct *ProtocolInterface;
/**
* Protocol interface structure
*/
struct ProtocolInterfaceStruct
{
/*Parse function*/
void (*Parse)(ADAPTER_PARAMS );
/*Send function*/
void (*Send)(ADAPTER_PARAMS );
/*Bypass function*/
void (*Receive)(ADAPTER_PARAMS );
};
/**
* Protocol structure
*/
struct ProtocolStruct
{
/*Protocol name*/
const char *name;
/*Protocol id*/
TE_PRODUCT_ID protocol_id;
/*Protocol interface*/
ProtocolInterface vtable;
};
protocol1.c
void protocol1_recv(ADAPTER_PARAMS )
{
printf("protocol 1 receive.\r\n");
}
void protocol1_send(ADAPTER_PARAMS )
{
printf("protocol 1 send.\r\n");
}
void protocol1_parse(ADAPTER_PARAMS )
{
printf("protocol 1 parse.\r\n");
}
static struct ProtocolInterfaceStruct protocol1_interface=
{
protocol1_parse,
protocol1_send,
protocol1_recv
};
static struct ProtocolStruct protocol1 =
{
"protocol 1",
protocol1,
&protocol1_interface
}
protocol2.c
void protocol2_recv(ADAPTER_PARAMS )
{
printf("protocol 2 receive.\r\n");
}
void protocol2_send(ADAPTER_PARAMS )
{
printf("protocol 2 send.\r\n");
}
void protocol2_parse(ADAPTER_PARAMS )
{
printf("protocol 2 parse.\r\n");
}
static struct ProtocolInterfaceStruct protocol2_interface=
{
protocol2_parse,
protocol2_send,
protocol2_recv
};
static struct ProtocolStruct protocol2 =
{
"protocol 2",
protocol2,
&protocol2_interface
}
protocol3.c
void protocol3_recv(ADAPTER_PARAMS )
{
printf("protocol 3 receive.\r\n");
}
void protocol3_send(ADAPTER_PARAMS )
{
printf("protocol 3 send.\r\n");
}
void protocol3_parse(ADAPTER_PARAMS )
{
printf("protocol 3 parse.\r\n");
}
static struct ProtocolInterfaceStruct protocol3_interface=
{
protocol3_parse,
protocol3_send,
protocol3_recv
};
static struct ProtocolStruct protocol3 =
{
"protocol 3",
protocol3,
&protocol3_interface
}
adapter.c
void protocol_parse(ADAPTER_PARAMS )
{
if(Protocol != NULL)
{
Protocol->vtable->parse(ADAPTER_PARAMS );
}
else
{
//error
}
}
void protocol_send(ADAPTER_PARAMS )
{
if(Protocol != NULL)
{
Protocol->vtable->send(ADAPTER_PARAMS );
}
else
{
//error
}
}
void protocol_recv(ADAPTER_PARAMS )
{
if(Protocol != NULL)
{
Protocol->vtable->recv(ADAPTER_PARAMS );
}
else
{
//error
}
}