您的位置:首页 > 编程语言

面向对象编程的设计思想

2016-07-02 15:48 309 查看
面向对象编程是一种设计思想,并不局限于语言。

无论是C++,Java,还是C语言,B语言,或者Shell,Perl,Python,甚至汇编语言,都可以实现面向对象编程。

“面向对象编程”是设计思想,C,C++是实现手段。

(相对来说C++更容易实现这种思想,而C比较麻烦)

如何实现面向对象编程?步骤如下:

1. 假设存在一个对象。初步设想它应该提供哪些服务,(把这个对象当成一个工具,或者是一个服务员)

2. 定义如何使用它的服务,细化为函数

(1). create/destroy:创建于销毁对象

(2). 其他功能函数:指该对象提供的服务

3. 选择一种实现方法,写代码完成上述函数接口

实例:DataStore

现在需求:存储一系列Student对象

第一步:定义服务

假设存在一个对象DataStore,它为我们提供Student对象的存储服务器,它提供以下的服务:

1. 可以向它加入一个对象

2. 可以按ID来查找一个对象

3. 可以按ID删除一个对象

4. 可以打印显示所有的对象

第二部:细化为函数

定义一个类型

struct DataStore
{

}


创建与销毁

DataStore ds_create();
void ds_destroy(DataStore *store);


其它功能函数:

(1)可以向它加入一个对象

void ds_add(DataStore * store,const Student *obj);


(2)可以按ID来查找一个对象

Student * ds_find(DataStore *store,int id);


(3)可以按ID删除一个对象

void ds_remove(DataStore *store,int id);


(4)可以打印显示所有的对象

void show_all(DataStore *store);


确定该对象的使用方式

//创建一个对象
DataStore *store=ds_create();
//调用ds_add
Student obj;
ds_add(store,&obj);
//销毁对象
ds_destroy(store);


实例:链表对象

定义接口高难度

第三步:选择一种实现

使用链表来实现

把相关数据放在DataStore对象里

struct DataStore
{
Student head;//存在一个有头链表
}


创建对象

DataStore *ds_create()
{
//动态创建对象
DataStore *store=(DataStore *)malloc(sizeof(DataStore));
//初始化
store->head.next=NULL;
return store;
}


可以按ID来查找一个记录

Student * ds_find(DataStore *store,int id)
{
Student *p=store->head.next;
while(p)
{
if(p->id==id)
return p;
p=p->next;
}
return NULL;
}


销毁对象

void ds_destroy(DataStore * store)
{
//释放所有相关资源
Student *p=store->head.next;
while(p)
{
Student *next=p->next;
free(p);
p=next;
}
free(store);
}


实现添加功能

void ds_add(DataStore *store,const Student *obj)
{
//创建对象、复制数据
Student *copy=(Student *)malloc(sizeof(Student));
*copy=*obj;
//插入一个对象到链表中
Student * cur=store->head.next;//当前节点current
Student * pre=&store->head;//上一个节点previous
while(cur)
{
if(obj->id<cur->id)//找到这个位置
break;
pre=cur;
cur=cur->next;//找到最后一个对象
}
//插入到pre节点的后面
copy->next=pre->next;
pre->next=copy;
}


遍历

void ds_print(DataStore *store,int id)
{
Student *p=store->head.next;
while(p)
{
printf("ID : %d,name:%s\n",p->id,p->name);
p=p->next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: