【原创】面向过程和面向对象编程比较---实例说明
0赞今天通过一个实际的案例来写一下面向对象和面向过程的区别。
1、面向过程设计
重点是细化一个过程
char *strcpy(char *, char *);
char *strcpy(char *dest, size_t n, const char *src)
{
char *p = dest;
int i = 0;
while(*src != '\0' && i
{
*p = *src;
p++;
src++;
i++;
}
return dest;
}
int ls()
{
}
int shellmain()
{
while(1)
{
fgets()
{
...
}
if(strcmp("ls", str))
{
pid_t = fork()
if(0 == pid)
{
ls();
exec(....);
}
}
}
}
A、降低代码规模
B、单个函数测试排错变得简单
C、代码复用率高了
1、调用形式
A、直接调用
B、间接调用
int fun()
{
}
typedef int (*PFUN) ();
int main()
{
PFUN pfun = fun;
fun();
pfun();
}
2、面向对象编程
strcuct obj{
PFUN pfun;
int num;
};
A、减少代码规模
封装抽象
struct cdev 表征的字符设备对象
struct cdev {
struct kobject kobj;
struct module *owner;
const struct file_operations *ops;
struct list_head list;
dev_t dev;
unsigned int count;
};
struct __link
{
struct __link *next;
};
struct cdev *cdev_alloc(void);
void cdev_init(struct cdev *, const struct file_operations *);
B、上层调用问题
注册回调
int cdev_add(struct cdev *, dev_t, unsigned);
内核的回调目的
(1)接口
(2)内核其他模块使用
=================================================================
drvopen()
{
1\找到对象
struct dev *obj = find_devobj();
obj->devopen();
}
struct file_operations fops ={
.open = drvopen,
};
struct cdev *cdev;
int init(void)
{
cdev = cdev_alloc();
cdev_init(cdev, &fops);
cdev_add(cdev, dev, 1);
}
void exit(void)
{
}
...
module_init(init);
module_init(exit);
--------------------------------------------
struct dev *arr[];
int dev_add(struct dev *);
--------------------------------------------
xxx_opne()
{
}
struct dev devobj{
.devopen = xxx_open,
}
int init(void)
{
dev_add(&obj);
}
void exit(void)
{
}
...
module_init(init);
module_init(exit);
===================================================================