设计模式之工厂模式-你以为我只有一个工厂吗?

一、工厂模式的概念

工厂模式是一种常用的创建型设计模式,它和简单工厂模式在结构上不同的地方就是工厂类得实现上,工厂模式的工厂类有一个抽象类和许多具体工厂类组成,具体工厂类继承抽象工厂类,这样就实现了解耦合,更方便后期的扩展和维护。

二、工厂模式使用场景

1、调用者需要知道具体工厂的职责,根据需要去实例化具体的工厂,生产出具体的某个产品。
2、当需要某一个产品时,生产者可以根据当前的生产产品的情况去判断使用哪一个工厂,使用工厂的主动权在生产者手中。

三、工厂模式构建方法

1、构建抽象工厂类

抽象工厂类是工厂模式的核心, 它是具体工厂的父类,所有的具体工厂类都必须实现该类中的对外接口。

2、构建具体工厂类

具体工厂类用于实现抽象工厂中的对外接口,包含对象创建的逻辑实现,创建所需的产品对象。

3、构建抽象产品类

工厂模式所创建的所有产品对象的父类,它负责描述所有实例所共有的公共接口。

4、构建具体产品类

工厂模式所创建的具体产品实例对象。

四、工厂模式的示例

// Factory.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
using namespace std;

// 水果基类
class Fruit
{
public:
	Fruit() {};
	~Fruit() {};
	virtual void printName()
	{
		cout << "My name is Fruit." << endl;
	}
};

// 具体水果-香蕉
class Banana : public Fruit
{
public:
	Banana() {};
	~Banana() {};
	void printName()
	{
		cout << "My name is Banana." << endl;
	}
};

// 具体水果-苹果
class Apple : public Fruit
{
public:
	Apple() {};
	~Apple() {};
	void printName()
	{
		cout << "My name is Apple." << endl;
	}
};

// 抽象工厂类
class Factory
{
public:
	Factory() {};
	~Factory() {};

	
	virtual Fruit *CreatFruit()
	{
		Fruit *pFruit = nullptr;
		pFruit = new Fruit();
		return pFruit;
	}
};

// 香蕉工厂类
class BananaFactory : public Factory
{
public:
	BananaFactory() {};
	~BananaFactory() {};


	virtual Banana *CreatFruit()
	{
		Banana *pFruit = nullptr;
		pFruit = new Banana();
		return pFruit;
	}
};

// 苹果工厂类
class AppleFactory : public Factory
{
public:
	AppleFactory() {};
	~AppleFactory() {};


	virtual Apple *CreatFruit()
	{
		Apple *pFruit = nullptr;
		pFruit = new Apple();
		return pFruit;
	}
};


#define DELETE_PTR(p) {if(p!=nullptr){delete (p); (p)=nullptr;}}
int main()
{
	Factory *pFactory = nullptr;
	Fruit *pFruit = nullptr;

	// 香蕉
	pFactory = new BananaFactory();
	pFruit = pFactory->CreatFruit();
	pFruit->printName();

	DELETE_PTR(pFruit);
	DELETE_PTR(pFactory);

	// 苹果
	pFactory = new AppleFactory();
	pFruit = pFactory->CreatFruit();
	pFruit->printName();

	DELETE_PTR(pFruit);
	DELETE_PTR(pFactory);

	std::cout << "Hello World!\n";

	getchar();
}

运行输出如下:
在这里插入图片描述

五、工厂模式的优缺点

优点:

克服了简单工厂模式违背开放-封闭原则的缺点,保留了封装对象创建过程的优点,降低了客户端和工厂的耦合性。

缺点:

当增加一个产品时,就要增加一个子工厂,增加了开发工作量。

能力有限,如有错误,多多指教。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值