定义:
定义一个用于创建对象的接口,让子类决定实例化哪一个类。工厂模式使一个类的实例化延迟到子类
目的作用:
1、解耦合
2、适应需求的变化,适应要创建的对象的具体类型经常变化
3、绕过对象的创建,提供一种“封装机制”来避免客户程序和这种“具体对象创建工作”的紧耦合
使用场景:
1、数据导出
2、支付接口
UML结构:
![[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-VIDQkAql-1589378984116)(E:\C++ Backend\MD\设计模式\三个设计模式.assets\image-20200513203616831.png)]](https://i-blog.csdnimg.cn/blog_migrate/7608dbf9e7eac2b18de1f2467049380a.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;
}
```