概念:简单工厂模式即,只需要输入实例化对象的名称,工厂类就可以实例化出来需要的类。
核心:实现工厂模式的核心就是多个派生类public继承基类,同时根据用户的需求在简单工厂类里面实例化基类的对象,从而根据基类里面的虚函数来实现对派生类的函数调用,同时实现多态。
如图:
利用简单计算器的实例来实现工厂模式:
#include<iostream>
using namespace std;
class _operator{
private:
int a;
int b;
public:
void setA(int _a) {a = _a;}
void setB(int _b) {b = _b;}
int GetA() {return a;}
int GetB() {return b;}
virtual int result() {return 0;}// 虚函数,为了通过基类的指针来调用派生类的对象
};
//通过对基类的虚函数进行不同的重写,在调用的时候可以根据不同的需求进行不同的实例化
class Add:public _operator{
int result() {return GetA() + GetB();}
};
class Sub:public _operator{
int result() {return GetA() - GetB();}
};
class Mul:public _operator{
int result() {return GetA() * GetB();}
};
class Div:public _operator{
int result() {return GetA() / GetB();}
};
class factory{
public:
static _operator* GetOperator(char ch){
_operator* p = NULL;
switch(ch){
case '+':
p = new Add();
break;
case '-':
p = new Sub();
break;
case '*':
p = new Mul();
break;
case '/':
p = new Div();
break;
default:
exit(1);
}
return p;
}
};
注:利用输入的不同,实例化不同的类对象,同时这些类有事通过继承基类的,那么从而在基类的指针来调用基类的虚函数,从而达到调用不同的派生类的目的。