用C语言实现面向对象<02>

xiaoee posted @ 2010年4月27日 09:41 in Coding My Mind with tags 面向对象 C语言 分层 封装 , 3239 阅读

其实这里讲的不是用C语言来实现面向对象,只是用了一点点面向对象的思想,来进行分层的模块化设计与简单的封装。

这里把一个软件分成了三层,用户层,接口层与实现层。上面是我自己根据理解自己起的名字。

还可以进行一下类比,就是用户,品牌P collapsedC厂商和硬件生产商。下面详细讲解:

首先是用户层:

#include "stdio.h"
#include "stdlib.h"

int main(void)
{
    printf("system start...\n");
	if (mod_init("mod_finished")<0) {
		exit(0);
	}
	mod_operation_1(0,1,2);
	mod_operation_2(0,1,2);
	mod_operation_3(0,1,2);
    return 0;
} 

然后是接口层,就是组装电脑的。。

#include <types.h>
#include <mod/mod.h>
#include "stdio.h"

extern struct mod_ops mod_finished;

static struct mod_ops *all_mods[] = {
    &mod_finished,
    NULL
};

static struct mod_ops mod_x;

#define MOD_OP(op, ...)					\
	(( mod_x.op != NULL ) ? mod_x.op( __VA_ARGS__ )	\
	: (typeof(mod_x.op(__VA_ARGS__))) 0)

/* Memory Management Interface */
int  mod_init(char *name)
{
    int i;
    for( i = 0; all_mods[i] != NULL; i++ ){
        mod_x = *all_mods[i];
        if( strcmp(mod_x.name, name) == 0 )
            break;
    }
    if(all_mods[i] == NULL ) {
        printf("Could not find mod:%s\n", name);
		return -1;
	}
    MOD_OP(init);
	return 0;
}

void mod_operation_1(type1_t para1,type2_t para2,type3_t para3)
{
    MOD_OP(operation_1, para1, para2, para3);
}

void mod_operation_2(type1_t para1,type2_t para2,type3_t para3)
{
    MOD_OP(operation_2, para1, para2, para3);
}

void mod_operation_3(type1_t para1,type2_t para2,type3_t para3)
{
    MOD_OP(operation_3, para1, para2, para3);
}

最下面是实现层,你可以有多个实现,就像你可以用不的硬件生产商生产的硬件组装成

功能相同的电脑一样。

#include <types.h>
#include <mod/mod.h>
#include "stdio.h"

void
init(void)
{
    printf("init not finished!\n");
	// you code here, to implement the init()
}

void
operation_1(type1_t para1,type2_t para2,type3_t para3)
{
    printf("operation_1 not finished\n");
	// you code here, to implement operation_1()
}

void
operation_2(type1_t para1,type2_t para2,type3_t para3)
{
    printf("operation_2 not finished\n");
	// you code here, to implement operation_2()
}

void
operation_3(type1_t para1,type2_t para2,type3_t para3)
{
    printf("operation_3 not finished\n");
	// you code here, to implement operation_3()
}

struct mod_ops mod_finished = {
    .name		= "mod_finished",
    .desc		= "This is the xxx mod",
    .init			= init,
	.operation_1		= operation_1,
	.operation_2		= operation_2,
	.operation_3		= operation_3
};

完整文件下载: arch-demo.tar.gz


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter