1.设计模式概念的引入
设计模式
2.c语言结构体的大多数用法
#include <stdio.h>
#include <stdlib.h>
struct animal
{
char name[128];
int age;
int sex;
void (*eat)();
void (*beat)();
};
void dogEat()
{
printf("狗吃是\n");
}
void catEat()
{
printf("猫吃鱼\n");
}
void personEat()
{
printf("人痴迷\n");
}
void dogBeat()
{
printf("咬你小蛋蛋\n");
}
void catBeat()
{
printf("抓你小蛋蛋\n");
}
void personBeat()
{
printf("猴子偷桃\n");
}
int main(void)
{
struct animal dog =
{
.eat = dogEat,//这里结构体只需要初始需要的部分
.beat = dogBeat
};
struct animal cat;
struct animal person;
//dog.eat = dogEat;
cat.eat = catEat;
person.eat = personEat;
//dog.beat = dogBeat;
cat.beat = catBeat;
person.beat = personBeat;
dog.eat();
cat.eat();
person.eat();
dog.beat();
cat.beat();
person.beat();
return 0;
}
3.工厂模式的引入
(1)工厂模式是最常用的的设计模式之一,这种类型的设计模式属于创建型模式,它提供了一种创建对象的(最佳)方式,在工厂模式中·,我们在创建对象时不会对客户端暴露创建逻辑,并且是通过使用一个共同的接口来指向新创建的对象。
4,工厂模式的实现
(1)头文件编写
struct animal
{
char name[128];
int age;
int sex;
void (*eat)();
void (*beat)();
struct animal *next;
};
struct animal * putCatInLink(struct animal *phead);
struct animal * putDogInLink(struct animal *phead);
struct animal * putPersonInLink(struct animal *phead);
struct animal * putHorseInLink(struct animal *phead);
(2)主函数编写
#include <stdio.h>
#include "animal.h"
#include <string.h>
struct animal *findUtilByName(char *str,struct animal *phead)
{
struct animal *tmp = phead;
if(phead == NULL)
{
printf("空\n");
return NULL;
}
else
{
while(NULL != tmp)
{
if(strcmp(tmp->name,str) == 0)
{
return tmp;
}
tmp = tmp->next;
}
return NULL;
}
}
int main()
{
char buf[127] = {'\0'};
struct animal *phead = NULL;
struct animal *ptmp;
phead = putCatInLink(phead);
phead = putDogInLink(phead);
phead = putPersonInLink(phead);
phead = putHorseInLink(phead);
while(1)
{
printf("请输入你要Tom,pototo,zzh,ma\n");
scanf("%s",buf);
ptmp = findUtilByName(buf,phead);
if(ptmp != NULL)
{
ptmp->beat();
ptmp->eat();
}
memset(buf,'\0',sizeof(buf));
}
return 0;
}
(3)猫的分文件编写
#include "animal.h"
#include <stdio.h>
void catEat()
{
printf("cat eat fish\n");
}
void catBeat()
{
printf("grab your dick\n");
}
struct animal cat= {
.eat = catEat,
.beat = catBeat,
.name = "Tom"
};
struct animal *putCatInLink(struct animal *phead)
{
if(phead == NULL)
{
phead = &cat;
return phead;
}
else
{
cat.next = phead;
phead = &cat;
return phead;
}
}
(4)其他分文件和猫的分文件相同这就实现了随时加入的工厂模式的引入。