一、什么是工厂模式?
是最常用的设计模式之一
这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
在工厂模式中,我们在创建对象时不会对客户端暴露创建逻辑,并且是通过使用一个共同的接口来指向新创建的对象。
二、工程模式简图

三、实例:
我们将实现输入对象名字,程序将根据对象姓名进行查找,查找完成在屏幕打印对象执行的动作,同时打印对象的姓名和年龄,若查找失败,则打印“no find name”
首先建立个5个.c文件和1个.h文件。如下:
1、Animal.h
该.h文件主要用于 类声明 以及几个 函数声明,同时可以将几个.C文件常用的.h文件包含于此。
#include<stdio.h>
#include<string.h>
struct Animal{
char name[128];
int age;
int sex;
int others;
void (*eat)();
void (*beat)();
void(*character)();
void (*test)();
struct Animal *next;
};
struct Animal* putHeadDogLink(struct Animal* head);
struct Animal* putHeadCatLink(struct Animal* head);
struct Animal* putHeadHumanLink(struct Animal* head);
struct Animal * findObjectName(char *name,struct Animal *head);
void catEat();
void dogEat();
void humanEat();
2、Dog.c
#include"Animal.h"
struct Animal dog={
.name="lala",
.age=5,
.eat=dogEat
};
void dogEat()
{
printf("eat baba\n");
}
struct Animal* putHeadDogLink(struct Animal* head)
{
if(head==NULL){
head=&dog;
return head;
}else{
dog.next=head;
head=&dog;
return head;
}
}
3、Cat.c
#include"Animal.h"
struct Animal cat={
.name="hihi",
.age=2,
.eat=catEat
};
void catEat()
{
printf("eat milk\n");
}
struct Animal* putHeadCatLink(struct Animal* head)
{
if(head==NULL){
head=&cat;
return head;
}else{
cat.next=head;
head=&cat;
return head;
}
}
4、Human.c
#include"Animal.h"
struct Animal human={
.name="bobo",
.age=18,
.eat=humanEat
};
void humanEat()
{
printf("eat rice\n");
}
struct Animal* putHeadHumanLink(struct Animal* head)
{
if(head==NULL){
head=&human;
return head;
}else{
human.next=head;
head=&human;
return head;
}
}
5、Function.c
#include"Animal.h"
struct Animal * findObjectName(char *name,struct Animal *head)
{
struct Animal *tmp=head;
if(head==NULL){
printf("The list is empty\n");
return NULL;
}else{
while(tmp!=NULL){
if(strcmp(tmp->name,name)==0){
return tmp;
}
tmp=tmp->next;
}
printf("no find name\n");
return NULL;
}
}
6、Main.c
#include "Animal.h"
int main()
{
char buf[128]={
'\0'};
struct Animal* head=NULL;
struct Animal* tmp=NULL;
head=putHeadDogLink(head);
head=putHeadCatLink(head);
head=putHeadHumanLink(head);
while(1){
memset(buf,'\0',sizeof(buf));
printf("input name:\n");
scanf("%s",buf);
tmp=findObjectName(buf,head);
if(tmp!=NULL){
tmp->eat();
printf("%s age:%d\n",tmp->name,tmp->age);
}
}
return 0;
}
注:在Liunx环境下进行编译时,首先将这几个文件存放在同一个文件夹,然后需使用gcc *.c
实验结果:
