简单工厂模式
简单工厂模式的实质是由一个工厂类根据传入的参数,动态决定应该创建哪一个产品类(这些产品类继承自一个父类或接口)的实例。
角色扮演
工厂(Creator)角色
简单工厂模式的核心,它负责实现创建所有实例的内部逻辑。工厂类的创建产品类的方法可以被外界直接调用,创建所需的产品对象。
抽象产品(Product)角色
简单工厂模式所创建的所有对象的父类,它负责描述所有实例所共有的公共接口。
具体产品(Concrete Product)角色
是简单工厂模式的创建目标,所有创建的对象都是充当这个角色的某个具体类的实例。
举例说明
父类提供通用方法接口函数shut
#ifndef FATHEROPERATION_H
#define FATHEROPERATION_H
class FatherOperation
{
public:
FatherOperation();
virtual ~FatherOperation();
virtual void shut()= 0;
protected:
private:
};
#endif // FATHEROPERATION_H
子类A实现父类方法
#ifndef OPERATION1_H
#define OPERATION1_H
#include "FatherOperation.h"
#include <stdlib.h>
#include <stdio.h>
class Operation1 :public FatherOperation
{
public:
Operation1();
virtual ~Operation1();
void shut(){
printf("shut A......\n");
}
protected:
private:
};
#endif // OPERATION1_H
子类B实现父类方法
#ifndef OPERATION2_H
#define OPERATION2_H
#include "FatherOperation.h"
#include <stdlib.h>
#include <stdio.h>
class Operation2 : public FatherOperation
{
public:
Operation2();
virtual ~Operation2();
void shut(){
printf("shut B......\n");
}
protected:
private:
};
#endif // OPERATION2_H
工厂创建各实例
#ifndef FACTORYSIMPLE_H
#define FACTORYSIMPLE_H
#include "FatherOperation.h"
#include "Operation1.h"
#include "Operation2.h"
class FactorySimple
{
public:
FactorySimple();
virtual ~FactorySimple();
static FatherOperation* CreateOperation(int typemode){
switch(typemode){
case 1:
return new Operation1;
break;
case 2:
return new Operation2;
break;
}
}
protected:
private:
};
#endif // FACTORYSIMPLE_H
demo:
#include "FactorySimple.h"
int main(){
FactorySimple * p = new FactorySimple();
p->CreateOperation(1)->shut();
p->CreateOperation(2)->shut();
return 0;
}
结果:
shut A......
shut B......
理解就是:一个工厂,多个产品。产品需要有一个虚基类。通过传入参数,生成具体产品对象,并利用基类指针指向此对象。通过工厂获取此虚基类指针,通过运行时多态,调用子类实现。
优点
工厂类是整个模式的关键.包含了必要的逻辑判断,根据外界给定的信息,决定究竟应该创建哪个具体类的对象.通过使用工厂类,外界可以从直接创建具体产品对象的尴尬局面摆脱出来,仅仅需要负责“消费”对象就可以了。而不必管这些对象究竟如何创建及如何组织的.明确了各自的职责和权利,有利于整个软件体系结构的优化。
缺点
由于工厂类集中了所有实例的创建逻辑,违反了高内聚责任分配原则,将全部创建逻辑集中到了一个工厂类中;它所能创建的类只能是事先考虑到的,如果需要添加新的类,则就需要改变工厂类了。
当系统中的具体产品类不断增多时候,可能会出现要求工厂类根据不同条件创建不同实例的需求.这种对条件的判断和对具体产品类型的判断交错在一起,很难避免模块功能的蔓延,对系统的维护和扩展非常不利;
应用场景
工厂类负责创建的对象比较少;
客户只知道传入工厂类的参数,对于如何创建对象(逻辑)不关心;
由于简单工厂很容易违反高内聚责任分配原则,因此一般只在很简单的情况下应用。