工厂模式

定义:
定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂模式使一个类的实例化延迟到子类
目的作用:
1、解耦合
2、适应需求的变化,适应要创建的对象的具体类型经常变化
3、绕过对象的创建,提供一种“封装机制”来避免客户程序和这种“具体对象创建工作”的紧耦合
使用场景:
1、数据导出
2、支付接口
UML结构:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-VIDQkAql-1589378984116)(E:\C++ Backend\MD\设计模式\三个设计模式.assets\image-20200513203616831.png)]

结构代码:
```c++
#include <iostream>

using namespace std;

class Export_File
{
public:
	Export_File() {}
	virtual ~Export_File() {}

	virtual bool Export(string data) = 0;
};

class Export_XML : public Export_File
{
public:
	Export_XML() {}
	~Export_XML() {}
	bool Export(string data)
	{
		printf("导出:%s 为XML格式\n", data.c_str());
		return true;
	}
};

class Export_TXT : public Export_File
{
public:
	Export_TXT() {}
	~Export_TXT() {}

	bool Export(string data)
	{


		printf("导出:%s为TXT格式\n", data.c_str());
		return true;
	}
};

class Export_factory
{

public:
	Export_factory() {}
	virtual ~Export_factory() {}

	virtual bool Export(string type, string data)
	{
		Export_File *export_file = nullptr;
		bool judge = false;

		export_file = factoryMethod(type);

		if (export_file)
		{
			judge = export_file->Export(data);
			delete export_file;
		}
		else
		{
			printf("没有对应的导出格式!\n");
		}

		return judge;
	}

protected:
	virtual Export_File *factoryMethod(string type)
	{
		Export_File *_export_file = nullptr;

		if (type == "xml")
		{
			_export_file = new Export_XML();
		}
		else if (type == "txt")
		{
			_export_file = new Export_TXT();
		}

		return _export_file;
	}
};

//在这继承原有的工厂方法实现代码只增不改,达到松耦合(开放封闭原则)

class Export_MDF : public Export_File
{
public:
	Export_MDF() {}
	~Export_MDF() {}

	bool Export(string data)
	{


		printf("导出:%s为mdf格式\n", data.c_str());
		return true;
	}
};

class Export_factory_ADD : public Export_factory
{

public:
	Export_factory_ADD() {}
	~Export_factory_ADD() {}

	bool Export(string type, string data)
	{
		Export_File *export_file = nullptr;
		bool judge = false;

		export_file = factoryMethod_add(type);

		if (export_file)
		{
			judge = export_file->Export(data);
			delete export_file;
		}
		else
		{
			printf("没有对应的导出格式!\n");
		}

		return judge;
	}

protected:
	Export_File *factoryMethod_add(string type)
	{
		Export_File *_export_file = nullptr;

		if (type == "mdf")
		{
			_export_file = new Export_MDF();
		}

		return _export_file;
	}
};

int main()
{

	Export_factory *factory = new Export_factory();

	factory->Export("xml", "<servlert></servert>");
	factory->Export("txt", "工厂模式");
	factory->Export("cc", "我是C++");

	printf("------------add--------------\n");

	Export_factory_ADD *factory_add = new Export_factory_ADD();
	factory_add->Export("mdf", "数据库文件");
	factory_add->Export("ldf", "我是事务日志文件");

	delete factory;
	delete factory_add;
	return 0;
}
```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值