创建型模式-工厂模式
工厂模式是一种创建型的设计模式,原理是父类提供一个创建对象的方法,允许子类去实现具体的实例化对象。通过此模式可减少创建和具体的产品之间的耦合关系。
适用场景:
1、当需求中无法预估对象确切类别及个别的依赖关系。例如: 如果需要向应用中添加一种新产品, 你只需要开发新的创建者子类, 然后重写其工厂方法即可。
2、当需要用户可以扩展我们软件库或者框架内部的应用。
实现过程:
1、创建一个工厂基类和产品基类。
2、实现继承于工厂类的工厂类和继承于产品的产品类。
3、对用工厂实现具体的产品。
关系图:
代码:
#include "DanLiMoShi.h"
#include "GongChangMoshi.h"
int main()
{
std::cout << "欢迎东哥来到设计模式的世界!\n";
factory* factoryBase = new factory; //基类工厂
product* productBase = factoryBase->createProduct();
cout << "factoryBase:" << productBase->m_name << endl;
factory* carFactory = new CarFactory;//汽车工厂创建
product* carProduct = carFactory->createProduct();
cout << "carProduct:" << carProduct->m_name << endl;
factory* phoneFactory = new PhoneFactory; //手机工厂
product* phoneProduct = phoneFactory->createProduct();
cout << "phoneFactory:" << phoneProduct->m_name << endl;
}
pragma once
#include <string>
using namespace std;
class product;//产品基类
class factory //工厂基类
{
public:
factory();
~factory();
virtual product* createProduct(); //创建具体的产品的方法
};
class CarFactory :public factory {
public:
CarFactory();
~CarFactory();
product* createProduct() override;
};
class PhoneFactory :public factory {
public:
PhoneFactory();
~PhoneFactory();
product* createProduct() override;;
};
class product {
public:
product(string name) { m_name = name; };
~product() {};
string m_name;
};
class CarProduct :public product {
public:
CarProduct(string name) :product(name) { m_name = name; };
~CarProduct() {};
string m_name;
};
class PhoneProduct :public product {
public:
PhoneProduct(string name,int age) :product(name) { m_name = name; m_age = age };
~PhoneProduct() {};
string m_name;
int m_age;
};
#include "GongChangMoshi.h"
factory::factory()
{
}
factory::~factory()
{
}
product* factory::createProduct()
{
return new product("基类产品");
}
CarFactory::CarFactory()
{
}
CarFactory::~CarFactory()
{
}
product* CarFactory::createProduct()
{
return new CarProduct("汽车产品");
}
PhoneFactory::PhoneFactory()
{
}
PhoneFactory::~PhoneFactory()
{
}
product* PhoneFactory::createProduct()
{
return new PhoneProduct("电话产品");
}