一.工厂模式定义
工厂模式(Factory Pattern)是 Java 中最常用的设计模式之一。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
在工厂模式中,我们在创建对象时不会对客户端暴露创建逻辑,并且是通过使用一个共同的接口来指向新创建的对象。
二.简单工厂模式练习
在工厂模式中,把所有的功能代码都写进我们的“工厂”中,再由main函数调用。
animal.h
#include <stdio.h>
struct Animal {
char name[128];
int afe;
int sex;
int others;
void (*peat)();
void (*pbeat)();
void (*test)();
struct Animal *next;
};
struct Animal* putCatLink(struct Animal *phead);
struct Animal* putDogLink(struct Animal * phead);
struct Animal* putPersonLink(struct Animal *phead);
cat.c
#include "animal.h"
void catEat()
{
printf("cat eat\n");
}
void catBeat()
{
printf("cat beat\n");
}
struct Animal Cat = {
.name = "Tom",
.peat = catEat,
.pbeat = catBeat
};
struct Animal* putCatLink(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("dog eat\n");
}
void dogBeat()
{
printf("dog beat\n");
}
struct Animal Dog = {
.name = "haoshan",
.peat = dogEat,
.pbeat = dogBeat
};
struct Animal* putDogLink(struct Animal *phead)
{
if(phead == NULL){
phead = &Dog;
return phead;
}else{
Dog.next = phead;
phead = &Dog;
return phead;
}
}
person.c
#include "animal.h"
void personEat()
{
printf("person eat\n");
}
void personBeat()
{
printf("person beat\n");
}
struct Animal Person = {
.name = "erzi",
.peat = personEat,
.pbeat = personBeat
};
struct Animal* putPersonLink(struct Animal *phead)
{
if(phead == NULL){
phead = &Person;
return phead;
}else{
Person.next = phead;
phead = &Person;
return phead;
}
}
main.c
#include "animal.h"
#include <string.h>
struct Animal* findUtilByName(char *str,struct Animal *phead)
{
struct Animal *tmp = phead;
if(phead == NULL){
printf("NULL\n");
return NULL;
}else{
while(tmp != NULL){
if(strcmp(tmp->name,str) == 0){
printf("strcmp success\n");
return tmp;
}
tmp = tmp->next;
}
return NULL;
}
}
int main()
{
char buf[128] = {'\0'};
struct Animal *phead = NULL;
struct Animal *ptmp;
phead = putCatLink(phead);
phead = putDogLink(phead);
phead = putPersonLink(phead);
while(1){
printf("please input:cat,dog person\n");
scanf("%s",buf);
ptmp = findUtilByName(buf,phead);
if(ptmp != NULL){
printf("success\n");
ptmp->pbeat();
ptmp->peat();
}
memset(buf,'\0',sizeof(buf));
}
return 0;
}
运行结果: