C++工厂模式个人总结

Posted 每天告诉自己要努力

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C++工厂模式个人总结相关的知识,希望对你有一定的参考价值。

通过阅读某些大型项目源码发现,工厂模式在分模块设计和可扩展的需求下是一个很好的帮手。下面是本人自己结合智能指针和类模板来进行分文件编写的demo。如果需要扩展具体的物品类(这里用car类为例),只需要增加新的factory工厂类和新的car物品类,在createObj 模板类提供了生成新物品类对象的接口,因此增加了新工厂类和新物品类后在main.cpp中直接改模板类型就可以实现扩展。
//main.cpp
#include <iostream>
#include <memory.h>
#include "car1.h"
#include "car2.h"
#include "factory1.h"
#include "factory2.h"
#include "factory3.h"
#include "kmain.hpp"
using namespace std;

int main() 
	//Base工厂T1,具体工厂T2,Base物品T3
	//生成的obj->m_car是对应物品的具体类对象
	unique_ptr<createObj<FactoryBase, Factory1, Car>> obj1(new createObj<FactoryBase, Factory1, Car>()); 
	obj1->m_car->play();

/*
	unique_ptr<createObj<FactoryBase, Factory2, Car>> obj2(new createObj<FactoryBase, Factory2, Car>());
	obj2->m_car->play();

	unique_ptr<createObj<FactoryBase, Factory3, Car>> obj3(new createObj<FactoryBase, Factory3, Car>());
	obj3->m_car->play();
*/
	return 0;

//kmain.hpp
#include <iostream>
#include <memory.h>
#include "car1.h"
#include "car2.h"
#include "factory1.h"
#include "factory2.h"
using namespace std;

//Base工厂T1,具体工厂T2,Base物品T3
template<class T1, class T2, class T3>
class createObj 
public:
	createObj()
		this->m_factory = createFactory();
		this->m_car = this->m_factory->create();
	
	shared_ptr<T1> createFactory()
		return make_shared<T2>();
	
public:
	shared_ptr<T1> m_factory;
	shared_ptr<T3> m_car;
;

物品类:

//CarBase.h
#pragma once
class Car 
public:
	virtual void play() = 0;
;
//car1.h
#pragma once
#include "CarBase.h"

class Car1 : public Car 
public:
	void play() override;
	~Car1();
;
//car1.cpp
#include "car1.h"
#include <iostream>
using namespace std;

void Car1::play() 
	cout << "Car1:奔驰" << endl;


Car1::~Car1() 
	cout << "奔驰释放了" << endl;

工厂类

//factorybase.h
#pragma once
#include <memory>
#include "CarBase.h"
class FactoryBase 
public:
	virtual std::shared_ptr<Car> create() = 0;
;
//factory1.h
#pragma once
#include "factorybase.h"

class Factory1 : public FactoryBase 
public:
	std::shared_ptr<Car> create() override;
	~Factory1();
;
//factory1.cpp
#include "factory1.h"
#include <memory>
#include <iostream>
#include "car1.h"

std::shared_ptr<Car> Factory1::create() 
		std::shared_ptr<Car> c1 = std::make_shared<Car1>();
		return c1;


Factory1::~Factory1() 
	std::cout << "工厂1释放了" << std::endl;

以上是关于C++工厂模式个人总结的主要内容,如果未能解决你的问题,请参考以下文章

嵌入式C语言设计模式 --- 关于工厂模式的总结

C++设计模式之-工厂模式的总结

学习 C++的用途,(前辈总结)

C++设计模式——简单工厂模式

设计模式 C++工厂方法模式

设计模式 C++工厂方法模式