工厂模式(factory pattern):
是最常用的设计模式之一
这种类型的设计模式属于创建型模式,他提供了一种创建对象的(最佳)方式
在工厂模式中,他们在创建对象时不会对客户端暴露创建逻辑,并且是通过使用一个共同的接口来指向新创建的对象
animal.h
#include <stdio.h>
struct Animal
{
char name[128];
int age; //成员属性
int sex;
int others;
void (*peat)();
void (*pbeat)(); //成员方法
void (*test)();
struct Animal *next;
};
struct Animal *putCatTolink(struct Animal *phead);
struct Animal *putDogTolink(struct Animal *phead);
struct Animal *putPersonTolink(struct Animal *phead);
cat.c
#include "animal.h"
#include <stdio.h>
void catEat()
{
printf("cat eat\n");
}
void catBeat()
{
printf("cat eat your brother\n");
}
struct Animal cat = {
.name = "cat",
.peat = catEat,
.pbeat = catBeat
};
struct Animal *putCatTolink(struct Animal *phead)
{
if(phead == NULL){
phead = &cat;
return phead;
}else{
cat.next = phead;
phead = &cat;
return phead;
}
}
dog.c
#include "animal.h"
#include <stdio.h>
void dogEat()
{
printf("dog eat\n");
}
void dogBeat()
{
printf("dog eat your brother\n");
}
struct Animal dog = {
.name = "dog",
.peat = dogEat,
.pbeat = dogBeat
};
struct Animal *putDogTolink(struct Animal *phead)
{
if(phead == NULL){
phead = &dog;
return phead;
}else{
dog.next = phead;
phead = &dog;
return phead;
}
}
person.c
#include "animal.h"
#include <stdio.h>
void personEat()
{
printf("person eat\n");
}
void personBeat()
{
printf("person eat your brother\n");
}
struct Animal person = {
.name = "person",
.peat = personEat,
.pbeat = personBeat
};
struct Animal *putPersonTolink(struct Animal *phead)
{
if(phead == NULL){
phead = &person;
return phead;
}else{
person.next = phead;
phead = &person;
return phead;
}
}
main.c
#include <string.h>
#include "animal.h"
struct Animal *findAnimalByName(struct Animal *phead,char *buf)
{
if(buf == NULL){
printf("It's NUll\n");
return NULL;
}else{
while(phead != NULL){
if(strcmp(phead->name,buf) == 0){
return phead;
}
phead = phead->next;
}
printf("No find !!!\n");
return NULL;
}
}
int main()
{
char buf[128] = {0};
struct Animal *temp = NULL;
struct Animal *phead = NULL; //初始化
phead = putDogTolink(phead); //将cat、dog、person做成一个链表
phead = putCatTolink(phead);
phead = putPersonTolink(phead);
while(1){ //业务
printf("===please chose cat/dog/person===\n");
scanf("%s",buf);
temp = findAnimalByName(phead,buf); //通过输入名字,找到对应的动物
if(temp != NULL){
temp->pbeat(); //找到后,做什么
temp->peat();
}
memset(buf,'\0',sizeof(128));
}
return 0;
}
运行结果: