设计模式
设计模式是软件开发人员在软件开发过程中面临的一般开发问题的解决方案。设计模式通常描述了一组相互紧密作用的类和对象;设计模式有23种;使代码更容易被他人理解,保证代码可靠性,程序的重要性。是通过代码设计经验总结而成,稳定性,拓展性更强。
工厂模式
工厂模式(Factory Pattern)是最常用的设计模式之一;这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式;在工厂模式中,创建对象时不会对客户端暴露创建逻辑,并且是通过使用一个共同的接口来指向新创建的对象。
结构体的新玩法
// 一个小例子,没有采用工厂模式
#include <stdio.h>
struct Animal{
char name[128];
int age;
int sex;
int others;
void (*peat)();
void (*beat)();
void (*test)();
};
void dogEat()
{
printf("狗吃骨头\n");
}
void catEat()
{
printf("猫吃鱼\n");
}
void dogBeat()
{
printf("咬\n");
}
void catBeat()
{
printf("挠\n");
}
int main()
{
struct Animal dog = {
.peat = dogEat,
.beat = dogBeat
};
struct Animal cat = {
.peat = catEat,
.beat = catBeat
};
dog.peat();
cat.peat();
dog.beat();
cat.beat();
}
采用工厂模式实现
按照需求一共创建了4个文件,包括3个 .c 文件和1个 .h文件(作为自己对工厂模式的入门学习)
// 此文件为 .c 文件
#include "animal.h"
#include <string.h>
struct Animal* findFromDefine(char* buf, struct Animal *head)
{
if(head == NULL)
{
printf("空\n");
return NULL;
}
else
{
while(head != NULL)
{
if(strcmp(buf, head->name) == 0)
{
return head;
}
head = head->next;
}
return NULL;
}
}
int main()
{
char buf[128] = {'\0'};
struct Animal* phead = NULL;
struct Animal* tmp = NULL;
phead = putCatInLink(phead);
phead = putDogInLink(phead);
while(1)
{
printf("Input:mycat or mydog\n");
scanf("%s", buf);
tmp = findFromDefine(buf, phead);
if(tmp != NULL)
{
tmp->peat();
tmp->beat();
}
memset(buf, '\0', sizeof(buf));
}
return 0;
}
// cat.c
#include "animal.h"
void catEat()
{
printf("猫吃鱼\n");
}
void catBeat()
{
printf("挠\n");
}
struct Animal cat = {
.name = "mycat",
.peat = catEat,
.beat = catBeat
};
struct Animal* putCatInLink(struct Animal *phead)
{
if(phead == NULL)
{
phead = &cat;
return phead;
}
else
{
cat.next = phead;
phead = &cat;
return phead;
}
}
// dog.c
#include "animal.h"
void dogEat()
{
printf("狗吃骨头\n");
}
void dogBeat()
{
printf("咬\n");
}
struct Animal dog = {
.name = "mydog",
.peat = dogEat,
.beat = dogBeat
};
struct Animal* putDogInLink(struct Animal* phead)
{
if(phead == NULL)
{
phead = &dog;
return phead;
}
else
{
dog.next = phead;
phead = &dog;
return phead;
}
}
// animal.h
#include <stdio.h>
struct Animal{
char name[128];
int age;
int sex;
int others;
void (*peat)();
void (*beat)();
void (*test)();
struct Animal *next;
};
struct Animal* putDogInLink(struct Animal* phead);
struct Animal* putCatInLink(struct Animal* phead);