工厂模式
在工厂模式中,我们在创建对象时不会对客户端暴露创建逻辑,并且是通过使用一个共同的接口来指向新创建的对象。工厂模式作为一种创建模式,一般在创建复杂对象时,考虑使用;在创建简单对象时,建议直接new完成一个实例对象的创建。
简单工厂模式
特点:在工厂类中做判断,从而创造相应的产品,当增加新产品时,需要修改工厂类。使用简单工厂模式,我们只需要知道具体的产品型号就可以创建一个产品。
缺点:工厂类集中了所有产品类的创建逻辑,如果产品量较大,会使得工厂类变的非常臃肿。
代码理解
#include <iostream>
using namespace std;
//定义产品类型信息
typedef enum
{
Lenovo,
Asus,
Apple
}Computer_Type;
//抽象产品类
class Computer
{
public:
virtual const string& type() = 0;
};
//具体的产品类
class Lenovo : public Computer
{
public:
Lenovo():Computer(),m_strType("Lenovo")
{
}
const string& type() override
{
cout << m_strType.data() << endl;
return m_strType;
}
private:
string m_strType;
};
//具体的产品类
class Apple : public Computer
{
public:
Apple():Computer(),m_strType("Apple")
{
}
const string& type() override
{
cout << m_strType.data() << endl;
return m_strType;
}
private:
string m_strType;
};
//工厂类
class ComputerFactory
{
public:
//根据产品信息创建具体的产品类实例,返回一个抽象产品类
Computer* createComputer(Computer_Type type)
{
switch(type)
{
case Lenovo:
return new Lenovo();
case Apple:
return new Apple();
default:
return nullptr;
}
}
};
int main()
{
ComputerFactory* factory = new ComputerFactory();
Computer* Lenovo = factory->createComputer(Lenovo);
Lenovo->type();
Computer* Apple = factory->createComputer(Apple);
Apple->type();
delete Lenovo;
Lenovo = nullptr;
delete Apple;
Apple = nullptr;
delete factory;
factory = nullptr;
return 0;
}