首页 > 代码库 > 设计模式-简单工厂模式

设计模式-简单工厂模式

简单工厂模式:是一种实例化对象的方式,只要输入实例化对象的名字,就可以通过工厂对象的相应工厂函数来制造你需要的对象

核心是,对于一个父类的多个继承子类,工厂对象的工厂函数根据用户输入,自动new 出一个子类对象 并返回其父类的指针,这样利用父类的指针执行父类的虚函数,就可以动态绑定子类的重写函数,从而实现多态.

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <iostream>
#include  <memory>

using namespace std;

class Operation
{
private:
	double A, B;
public:
	double GetA() const {return A;}
	double GetB() const {return B;}
	void SetA(double x) {A=x;}
	void SetB(double y) {B=y;}
	double virtual GetResult(){return 0;}
	Operation():A(0), B(0){}
};

class Add : public Operation
{
public:
	double GetResult()
	{
		return GetA()+GetB();
	}
};

class Sub : public Operation
{
public:
	double GetResult()
	{
		return GetA()-GetB();
	}
};

class Mul : public Operation
{
public:
	double GetResult()
	{
		return GetA()*GetB();
	}
};

class Div : public Operation
{
public:
	double GetResult()
	{
		return GetA()/GetB();
	}
};

class SimpleFactory
{
public:
	static Operation * CreateOpeartor(char ch)
	{
		Operation * p;
		switch(ch)
		{
		case ‘+‘:
			p = new Add();
			break;
		case ‘-‘:
			p = new Sub();
			break;
		case ‘*‘:
			p = new Mul();
			break;
		case ‘/‘:
			p = new Div();
			break;
		}
		return p;
	}
};

int main(int argc, char *argv[])
{
	double A = 0;
	double B = 0;
	char ch = ‘\0‘;
	cin>>A>>ch>>B;

	tr1::shared_ptr<Operation> op(SimpleFactory::CreateOpeartor(ch));
	op->SetA(A);
	op->SetB(B);
	cout<<op->GetResult()<<endl;
	system("pause");
	return 0;
}

  

设计模式-简单工厂模式