简单工厂

#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();
	
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值