参考《大话设计模式》
工厂方法:定义一个用于创建对象的接口,让子类决定实例化哪一个类,工厂方法模式使一个类的实例化延迟到其子类;
factory.h
#ifndef _FACTORY_H_
#define _FACTORY_H_
class Operation; //前向声明
class CFactory
{
public:
CFactory() {}
virtual ~CFactory() {}
virtual Operation* CreateOperation() {return NULL;}
};
#endif
factory_add.h
#ifndef _FACTORY_ADD_H_
#define _FACTORY_ADD_H_
#include "factory.h"
#include "operation_add.h"
class CFactoryAdd : public CFactory
{
public:
CFactoryAdd() {}
virtual ~CFactoryAdd() {}
virtual Operation* CreateOperation()
{
return new OperationAdd;
}
};
#endif
factory_sub.h
#ifndef _FACTORY_SUB_H_
#define _FACTORY_SUB_H_
#include "factory.h"
#include "operation_sub.h"
class CFactorySub:public CFactory
{
public:
CFactorySub() {}
virtual ~CFactorySub() {}
virtual Operation* CreateOperation()
{
return new OperationSub;
}
};
#endif
operation.h
#ifndef _OPERATION_H_
#define _OPERATION_H_
class Operation
{
public:
Operation() {}
Operation(double num1,double num2)
:num1_(num1)
,num2_(num2_)
{
}
virtual ~Operation() {}
virtual double GetResult() { return 0; }
double get_num2() const { return num2_; }
void set_num2(double val) { num2_ = val; }
double get_num1() const { return num1_; }
void set_num1(double val) { num1_ = val; }
protected:
double num1_;
double num2_;
};
#endif
operation_add.h
#ifndef _OPERATION_ADD_H_
#define _OPERATION_ADD_H_
#include "operation.h"
class OperationAdd: public Operation
{
public:
OperationAdd() {}
virtual ~OperationAdd() {}
virtual double GetResult() { return num1_ + num2_; }
};
#endif
operation_sub.h
#ifndef _OPERATION_SUB_H_
#define _OPERATION_SUB_H_
#include "operation.h"
class OperationSub: public Operation
{
public:
OperationSub() {}
virtual ~OperationSub() {}
virtual double GetResult() { return num1_ - num2_; }
};
#endif
main.cpp
#include <iostream>
#include "factory_add.h"
#include "factory_div.h"
#include "factory_mul.h"
#include "factory_sub.h"
#include "Operation.h"
int main()
{
CFactory *factory_add = new CFactoryAdd;
Operation * oper = factory_add->CreateOperation();
oper->set_num1(56);
oper->set_num2(54);
std::cout<<oper->GetResult()<<std::endl;
delete factory_add;
return 0;
}