一、简介
适配器模式(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
}
}
以上就是良许教程网为各位朋友分享的Linu系统相关内容。想要了解更多Linux相关知识记得关注公众号“良许Linux”,或扫描下方二维码进行关注,更多干货等着你 !