简单工厂模式属于类的创建型模式,又叫静态工厂方法模式。通过站门定义一个类来负责创建其他类的实例,被创建的实例通常具有共同的父类。
1.工厂角色:简单工厂模式的核心,他负责实现创建所有实例的内部逻辑,工厂类可以被外界直接调用,创建所需的产品对象。
2.抽象角色:简单工厂所创建的所有对象的父类,它负责描述所有实例共有的公共接口。
3.具体产品角色:简单工厂模式所创建的具体实例对象。

简单工厂的优缺点:在这个模式中,工厂类是整个模式的关键所在。它包含必要的逻辑判断,能够根据外界给定的信息,决定究竟应该创建哪个具体类的对象。用户可以在使用时直接根据工厂去创建所需要的实例,而无需了解这些对象是如何被创建以及被组织的。有利于整个软件体系结构的优化。不难发现,简单工厂的缺点也正体现在其它工厂上,由于工厂类集中了所有实例的创建逻辑,所以“高内聚”方面做的不好。另外,当系统中的具体产品不断增多时,可能出现要求工厂类也需要做出相应的扩展,扩展性不好。
具体实现的例子:
#include <iostream>
#include <string>
using namespace std;
class Fruit{
public:
virtual void getFruit(){
cout<<"Fruit::getFruit"<<endl;
}
};
class Pear:public Fruit{
public:
virtual void getFruit(){
cout<<"Pear::getFruit"<<endl;
}
};
class Banana:public Fruit{
public:
virtual void getFruit(){
cout<<"Banana::getFruit"<<endl;
}
};
// 工厂类:与实际的Pear、Banana的关系为依赖关系
class Factory{
public:
static Fruit *create(string name){
if(name == "Pear"){
return new Pear;
}else if(name == "Banana"){
return new Banana;
}else{
return nullptr;
}
}
};
int main(int argc, const char * argv[]) {
Fruit *f = nullptr;
f = Factory::create("Pear");
f->getFruit();
f = Factory::create("Banana");
f->getFruit();
return 0;
}
运行结果:

浙公网安备 33010602011771号