适配器模式C语言实现

这篇博客介绍了如何用C语言实现适配器模式,提供了包括`forwardplayer`、`centerplayer`、`guardsplayer`、`foreigncenterplayer`以及适配器`foreigncenteradapter`的源码,并附带测试文件`test.c`和`Makefile`。作者鼓励读者下载源码进行学习和交流。
摘要由CSDN通过智能技术生成

【说明】适配器模式的C语言实现,改写自http://blog.csdn.net/sx_wpc/article/details/7688128一文的代码。

【代码清单】

typedef.h

#ifndef __TYPEDEF_H__
#define __TYPEDEF_H__

#include <stdio.h>
#include <stdlib.h>

#ifdef __cplusplus
extern "C" {
#endif

typedef enum _Ret
{
	RET_OK,
	RET_FAIL
}Ret;

#define return_if_fail(p)\
	if(!(p)){\
	printf("%s:%d Warning:"#p"Failed\n",__func__,__LINE__);\
	return;}
#define return_val_if_fail(p, ret)\
	if(!(p)){\
	printf("%s:%d Warning:"#p"Failed\n",__func__,__LINE__);\
	return (ret);}
#define SAFE_FREE(p) if(p != NULL){free(p); p = NULL;}

#ifdef __cplusplus
}
#endif

#endif


player.h

#ifndef __PLAYER_H__
#define __PLAYER_H__

#include "typedef.h"

#ifdef __cplusplus
extern "C" {
#endif

struct _Player;
typedef struct _Player Player;

struct _Player
{
	char *name;
	void (*attack)(void *player);
	void (*defend)(void *player);
	void (*destroy)(void *player);
};

static inline void player_attack(Player *thiz)
{
	return_if_fail(thiz != NULL);
	if(thiz->attack != NULL)
	{
		thiz->attack(thiz);
	}
}

static inline void player_defend(Player *thiz)
{
	return_if_fail(thiz != NULL);
	if(thiz->defend != NULL)
	{
		thiz->defend(thiz);
	}
}

static inline void player_destroy(Player *thiz)
{
	return_if_fail(thiz != NULL);
	if(thiz->destroy != NULL)
	{
		thiz->destroy(thiz);
	}
}

#ifdef __cplusplus
}
#endif

#endif


forwardsplayer.h

#ifndef __FORWARDSPLAYER_H__
#define __FORWARDSPLAYER_H__

#include "player.h"

#ifdef __cplusplus
ext
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值