为什么我会学习设计模式?
主要原因是以前写代码乱写,看起来杂乱无章,添加和拓展功能的时候会导致其他部分的代码被破坏,所以才会学习设计模式,设计模式有23种,目前先学习一下简单工厂模式。
什么是设计模式?
设计模式,是一套被反复使用、多数人知晓的、经过分类的、代码设计经验的总结。是一系列的编程的思想。
什么是工厂模式?
工厂模式,是最常用的设计模式之一,种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
在工厂模式中,我们在创建对象时不会对客户端暴露创建逻辑,并且是通过使用一个共同的接口来指向新创建的对象。如果想增加一个产品,只要扩展一个工厂类就可以.
通过给API传入不同的参数,工厂生产出不同的东西。
比如,您需要一批果汁,可以直接告诉工厂你需要一批果汁就行,而不用去管这些果汁是怎么做出来的,以及制作榨果汁里面的具体实现。
示例代码
设有一个果汁的工厂,这个工厂要生产梨汁和苹果汁,这就用到了简单工厂模式。
1.先创建一个工厂的类(结构体),它可以根据参数的不同返回不同类的实例。
#include<stdio.h>
#include<string.h>
//工厂类
struct Fruit
{
char* name;//货品名称
void(*process)();//榨汁
struct Fruit* next;
};
struct Fruit* putPearlnLink(struct Fruit* head);
struct Fruit* putApplelnLink(struct Fruit* head);
2.使用工厂类创建对象
pear.c
#include"fruit.h"
void pearProcess()
{
printf("梨汁\n");
}
struct Fruit pear = {
.name = "梨",
.process = pearProcess
};
struct Fruit* putPearlnLink(struct Fruit* head)
{
if (head == NULL)
{
head = &pear;
return head;
}
else {
pear.next = head;
head = &pear;
return head;
}
}
apple.c
#include"fruit.h"
void AppleProcess()
{
printf("苹果汁\n");
}
struct Fruit apple = {
.name = "苹果",
.process = AppleProcess
};
struct Fruit* putApplelnLink(struct Fruit* head)
{
if (head == NULL)
{
head = &apple;
return head;
}
else {
apple.next = head;
head = &apple;
return head;
}
}
3.主程序
#include"fruit.h"
struct Fruit* findUtilByName(char* str, struct Fruit* head)
{
struct Fruit* tmp = head;
if (head == NULL)
{
printf("空\n");
return NULL;
}
else {
while (tmp != NULL)
{
if (strcmp(tmp->name,str) == 0)
{
return tmp;
}
tmp = tmp->next;
}
return 0;
}
}
int main()
{
struct Fruit* head = NULL;
struct Fruit* tem = NULL;
char buf[128] = {'\0'};
head = putPearlnLink(head);
head = putApplelnLink(head);
while (1)
{
printf("请输入要制作的果汁:1.苹果,2.梨\n");
scanf("%s", buf);
tem = findUtilByName(buf, head);
if (tem != NULL)
{
tem->process();
}
printf("\n");
memset(buf,'\0',sizeof(buf));
}
return 0;
}
运行结果。