最简便的工厂模式
工厂模式
什么是对象 什么是类
c 其实也是面向过程的 或者面向对象的编程
1 一个调用者想创建一个对象,只要知道其名称就可以了。
2、扩展性高,如果想增加一个产品,只要扩展一个工厂类就可以。
3、屏蔽产品的具体实现,调用者只关心产品的接口。
也就是 我们只需要知道名字 其他的不用关心 不用去关心封装过程 和内容
调用名字可以了
链表的头插法
用 链表的头插法 把各种的名 加入链表中来
思路
现在 最右的 还没加入
第二个为头结点 所以第一个的下一个地址是头结点
多个也是这样 分别头插法就行了
输入名字 找封装函数
anminal.h
#include <stdio.h>
#include <string.h>
struct aminal{
char name[32];
void (*eat)();
void (*beat)();
struct aminal *next;
};
struct aminal*catLinkNodes(struct aminal *head);
struct aminal*dogLinkNodes(struct aminal *head);
cat.c
#include "anminal.h"
void catEat()
{
printf("cat eat fish\n");
}
void catBeat()
{
printf("cat beat rice\n");
}
struct aminal cat = {
.name = "cat",
.eat = catEat,
.beat = catBeat
};
struct aminal *catLinkNodes(struct aminal *head)
{
struct aminal *tmp = head;
if(head == NULL){
head=&cat;
return head;
}else{
cat.next = head;
head =&cat;
return head;
}
}
dog.c
#include "anminal.h"
void dogEat()
{
printf("dog eat shi\n");
}
void dogBeat()
{
printf("dog beat xiaodidi\n");
}
struct aminal dog = {
.name = "dog",
.eat = dogEat,
.beat = dogBeat
};
struct aminal *dogLinkNodes(struct aminal *head)
{
struct aminal *tmp = head;
if(head == NULL){
head=&dog;
return head;
}else{
dog.next = head;
head =&dog;
return head;
}
}
mian.c
注意: 头结点不存在数据 所以把头结点的地址赋值另一个变量 间接把头结点的值 打印出来
#include "anminal.h"
struct aminal* LookforAminaByname(struct aminal *head,char name[])
{
struct aminal *tmp=head;
if(head == NULL){
return NULL;
}else{
while (tmp!=NULL)
{
if(!strcmp(tmp->name,name)){
return tmp;
}
tmp =tmp->next;
}
return NULL;
}
}
void main()
{
struct aminal *Aminalphead=NULL;
struct aminal *tmp=NULL;
char name[32]={'\0'};
Aminalphead = catLinkNodes(Aminalphead);
Aminalphead = dogLinkNodes(Aminalphead); //头插法进链表
while(1){
printf("input :cat-----dog--------\n");
scanf("%s",name);
getchar();
tmp=LookforAminaByname(Aminalphead,name);//通过strcmp 把 输入的名字 和 封装的名字 比较 得出数据
/*头不为空 就 调用函数 实现 */
if(tmp!=NULL){
tmp->beat();
tmp->eat();
}
}
}
1 把文件夹拉虚拟机
2 gcc *.c 编译 当前页面下的所有的c文件