设计模式---简单工厂模式

为什么我会学习设计模式?

主要原因是以前写代码乱写,看起来杂乱无章,添加和拓展功能的时候会导致其他部分的代码被破坏,所以才会学习设计模式,设计模式有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;
}

运行结果。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

走下去-别回头

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值