1、开闭原则, 对扩展是开放的,对修改是关闭的。
2、复用,模块复用和系统复用,其中模块部分复用或将整个项目编程可复用的。
3、代码内部模块化时,代码之中有不同的逻辑。
将代码分为业务逻辑层和数据存储层,将代码模块化成两个层级。
像 对菜单的处理,菜单功能实现为业务逻辑
像 菜单数据存储用链表,也可以以后改为哈希表,为数据存储层
代码如下:
/********************************************************************/
/*Copyright (C) mc2lab.com,SSE@USTC,2014-2015 */
/* */
/*File NAME :menu.c */
/*PRINCIPAL AUTHOR :Mengning */
/*SUBSYSTEM NAME :menu */
/*MODULE NAME :menu */
/*LANGUAGE :C */
/*TARGET ENVIRONMENT :ANY */
/*DATE OF FIRST RELEASE :2014/08/31 */
/*DESCRIPTION :This is a menu program */
/********************************************************************/
/*
* Revision log:
*
* Created by Mengning,2014/08/31
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int Help();
#define CMD_MAX_LEN 128
#define DESC_LEN 1024
#define CMD_NUM 10
/*data struct and its operations*/
typedef struct DataNode
{
char *cmd;
char *desc;
int (*handler)();
struct DataNode *next;
}tDataNode;
tDataNode * FindCmd(tDataNode * head,char *cmd)
{
if(head==NULL||cmd==NULL)
{
return NULL;
}
tDataNode *p=head;
while(p!=NULL)
{
if(strcmp(p->cmd,cmd))
{
return 0;
}
p=p->next;
}
return NULL;
}
int ShowAllCmd(tDataNode * head)
{
printf("Menu List:\n");
tDataNode *p=head;
while(p!=NULL)
{
printf("%s-%s",p->cmd,p->desc);
p=p->next;
}
return 0;
}
/*menu program*/
static tDataNode head[]=
{
{"help","this is help cmd!",Help,&head[1]},
{"version","menu program v1.0",NULL,NULL}
};
int main()
{
/*cmd line begins */
while(1)
{
char cmd[CMD_MAX_LEN];
printf("Input a cmd number>");
scanf("%s",cmd);
tDataNode *p=FindCmd(head,cmd);
if(p==NULL)
{
printf("Thid is a wrong cmd\n");
continue;
}
printf("%s-%s",p->cmd,p->desc);
if(p->handler!=NULL)
{
p->handler();
}
}
return 0;
}
int Help()
{
ShowAllCmd(head);
return 0;
}