代码结构:
头文件:
Interface1.h:总接口,定义Interface类
Factory1.h: 简单工厂类
OperateAdd.h: 继承Interface类实现+的操作。
OperateMin.h: 继承Interface类实现-的操作
源文件:
Interface1.cpp
//Factory1.cpp(Factory.h中实现内联,因此不需要对应的CPP文件)
OperateAdd.cpp
OperateMin.cpp
UseFactory1.cpp:调试入口
简单工厂模式简介:
公共的接口Interface类,分别派生出不同的操作类,实现同一个接口,实现派生类之间的解耦关系。再定义一个工厂类,利用C++多态的特性,从工厂中根据不同的类型“取出”不同的操作。
Interface1.h:
#pragma once
class Interface
{
public:
virtual int GetResult(const int& A, const int& B);
};
Interface1.cpp:
#include"Interface1.h"
#include<iostream>
using namespace std;
int Interface::GetResult(const int& A, const int& B)
{
cout << "This is Interface::GetResult" << endl;
return -1;
}
OperateAdd.h:
#pragma once
#include"Interface1.h"
class OperateAdd:public Interface
{
public:
virtual int GetResult(const int& A, const int & B);
};
OperateAdd.cpp
#include"OperateAdd.h"
#include<iostream>
using namespace std;
int OperateAdd::GetResult(const int& A, const int& B)
{
cout << "This is OperaterAdd::GetResult" << endl;
return A + B;
}
OperateMin.h:
#pragma once
#include"Interface1.h"
class OperateMin :public Interface
{
public:
virtual int GetResult(const int& A, const int & B);
};
OperateMin.cpp:
#include"OperateMin.h"
#include<iostream>
using std::cout;
using std::endl;
int OperateMin::GetResult(const int& A, const int& B)
{
cout << "This is OperateMin::GetResult" << endl;
return A - B;
}
Factory1.h:工厂类
#pragma once
#include"Interface1.h"
#include"OperateAdd.h"
#include"OperateMin.h"
class EasyFactory {
public:
Interface* GetOperate(int type)
{
switch (type)
{
case 1:
return new Interface;
case 2:
return new OperateAdd;
case 3:
return new OperateMin;
default:
return NULL;
}
}
};
UseFactory1.cpp:调试入口
#include<iostream>
#include"Interface1.h"//这里的依赖项不需要关注OperateAdd.h和OperateMin.h,实现解耦
#include"Factory1.h"
using namespace std;
#include<stdio.h>
//int ShowResult(Interface& Intf,int(Interface::*p)(const int& A, const int& B), const int& A, const int& B);
int ShowResult(Interface& Intf, const int& A, const int& B);
int main(int argc, char * argv[])
{
int numb1 = 10;
int numb2 = 3;
int type = 0;
cout << "Input an type:";
cin >> type;
EasyFactory ef;
Interface *intf = ef.GetOperate(type);
//ShowResult(intf, &Interface::GetResult, numb1, numb2);
if (intf == NULL)
return -1;
ShowResult(*intf, numb1, numb2);
delete intf;
cout << "press any key to continue" << endl;
cin.get();
cin.get();
return 0;
}
//类对象和类的成员函数值之间不是包含的关系,只是成员函数能够调用而已。外侧不可见,因此不能使用&obj.func的形式取到函数地址。
//int ShowResult(Interface& Intf,int(Interface::*p)(const int& A, const int& B), const int& A, const int& B)
//{
// cout << "The result is [" << (Intf.*p)(A, B) << "]\n";
// return (Intf.*p)(A, B);
//}
//
int ShowResult(Interface& Intf, const int& A, const int& B)
{
int tmp = Intf.GetResult(A, B);
cout << "Result is [" << tmp << "]" << endl;
return tmp;
}