(转自大话设计模式C++)
主要用于创建对象。新添加类时,不会影响以前的系统代码。核心思想是用一个工厂来 根据输入的条件产生不同的类,然后根据不同类的 virtual 函数得到不同的结果。
GOOD:适用于不同情况创建不同的类时
BUG:客户端必须要知道基类和工厂类,耦合性差
class COperation
{
public:
int m_nFirst;
int m_nSecond;
virtual double GetResult()
{
double dResult=0;
return dResult;
}
};
//加法
class AddOperation : public COperation
{
public:
virtual double GetResult()
{
return m_nFirst+m_nSecond;
}
};
//减法
class SubOperation : public COperation
{
public:
virtual double GetResult()
{
return m_nFirstm_nSecond;
}
};
//工厂类
class CCalculatorFactory
{
public:
static COperation* Create(char cOperator);
};
COperation* CCalculatorFactory::Create(char cOperator)
{
COperation *oper;
switch (cOperator)
{
case '+':
oper=new AddOperation();
break;
case '':
oper=new SubOperation();
break;
default:
oper=new AddOperation();
break;
}
return oper;
}
客户端
int main()
{
int a,b;
cin>>a>>b;
COperation * op=CCalculatorFactory::Create('-'); //客户端必须要知道基类和工厂类,耦合性差
op>m_nFirst=a;
op>m_nSecond=b;
cout<<op>GetResult()<<endl;
return 0;
}
以下转一道MTK的笔试题说明工厂类(文章来源http://blog.csdn.net/challenge_c_plusplus/article/details/6681729)
简单工厂方法示例程序:
#include "Factory.h"
#include "MTK.h"
int main()
{
MTK *pM1=Factory::make("DVD");
MTK *pM2=Factory::make("Mobile");
MTK *pM3=Factory::make("Television");
pM1->Production();
pM2->Production();
pM3->Production();
return 0;
}
输出结果:
结果及简单分析:(其实就是简单的动态绑定练习)
#ifndef _FACTORY_H
#define _FACTORY_H
#include "MTK.h"
class Factory{
public:
static MTK * make(const char *product);
};
#endif
#include "Factory.h"
#include <string>
#include "DVD.h"
#include "Mobile.h"
#include "Television.h"
MTK * Factory::make(const char *product)
{
if(!strcmp(product,"DVD")){
return new DVD;
}
else if(!strcmp(product,"Mobile")){
return new Mobile;
}
else if(product,"Television"){
return new Television;
}
else
return NULL;
}
==============================================
#ifndef _MTK_H
#define _MTK_H
class MTK{
public:
virtual void Production();
};
#endif
#include "MTK.h"
void MTK::Production(){}
=================================
#ifndef _DVD_H
#define _DVD_H
#include "MTK.h"
class DVD : public MTK{
public:
void Production();
};
#endif
#include "DVD.h"
#include "iostream"
void DVD::Production()
{
std::cout << "DVD Product" << std::endl;
}
===================================
#ifndef _MOBILE_H
#define _MOBILE_H
#include "MTK.h"
class Mobile : public MTK{
public:
void Production();
};
#endif
#include "Mobile.h"
#include "iostream"
void Mobile::Production()
{
std::cout << "Mobile Product" << std::endl;
}
=====================================
#ifndef _TELEVISION_H
#define _TELEVISION_H
#include "MTK.h"
class Television : public MTK{
public:
void Production();
};
#endif
#include "Television.h"
#include "iostream"
void Television::Production()
{
std::cout << "Television Product" << std::endl;
}