简单工厂

#pragma once

#include <iostream>

/*
	面向对象三个特性: 封装,继承,多态

	业务逻辑和界面逻辑分开 ----- 封装
	

*/

/*
	运算类
	将每个运算符抽象成一个类
*/
class Operation
{
	public:
		Operation():m_lhs(0.0), m_rhs(0.0){}
	
	public:
		virtual double get_result()
		{
			return 0.0;
		}

	public:
		void set_lhs(const double &lhs){ m_lhs = lhs; }
		void set_rhs(const double &rhs){ m_rhs = rhs; }

	protected:
		double m_lhs;
		double m_rhs;
};

/*
	加法类
*/
class OperationAddition : public Operation
{
	public:
		virtual double get_result()
		{
			return m_lhs + m_rhs;
		}
};

/*
   减法类
*/
class OperationSubtraction : public Operation
{
	public:
		virtual double get_result()
		{
			return m_lhs - m_rhs;
		}
};

/*
   问题: 根据运算符,怎么选择相应的算法类?

   解决方法: 简单工厂
   
*/

class OperationFactory
{
	public:
		static Operation * get_operation(char opt)
		{
			Operation *lpOpt = NULL;
			
			switch(opt)
			{
				case '+':
					{
						lpOpt = new OperationAddition;
					}
				break;

				case '-':
					{
						lpOpt = new OperationSubtraction;
					}
				break;
					
			}
			return lpOpt;
		}
};


void TestOperation();


#include "dm_chp_01.hpp"

#include <iostream>
using namespace std;

void TestOperation()
{
	double lhs, rhs;
	char opt;
	
	cout << "输入一个操作数: " << flush;
	if(cin)
		cin >> lhs;
	cout << endl;

	cout << "输入一个操作符号(+ - * /): " << flush;
	if(cin)
		cin >> opt;
	cout << endl;

	cout << "输入一个操作数: " << flush;
	if(cin)
		cin >> rhs;
	cout << endl;

	// 客户端运行代码
	Operation *lpOpt = OperationFactory::get_operation(opt);
	lpOpt->set_lhs(lhs);
	lpOpt->set_rhs(rhs);
	cout << "结果: " << lpOpt->get_result() << endl;

	
	getchar();
	
}




你可能感兴趣的:(简单工厂)