-->计算器
通过封装、继承、多态把程序的耦合度降低,使程序容易修改,易于复用
解决方案目录
项目属性
框架:.NET Framework 4.6.1 输出类型:控制台应用程序
运算相关的类:Operation.cs
运算类为父类,包含定义字段、属性、方法等
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SimpleFactory
{
//原本只是加一个功能,却使原有的运行良好的功能代码产生了变化,风险大
/// <summary>
/// 运算类
/// </summary>
public class Operation
{
private double _numberA = 0; //定义字段
private double _numberB = 0;
public double NumberA //定义属性
{
get { return _numberA; }
set { _numberA = value; }
}
public double NumberB
{
get { return _numberB; }
set { _numberB = value; }
}
public virtual double GetResult()//定义方法 virtual 方法可以重写 虚方法
{
double result = 0;
return result;
}
}
/// <summary>
/// 加法类,继承运算类
/// </summary>
class OperationAdd : Operation
{
public override double GetResult() //定义方法 override方法重写了一个基类方法(如果方法被重写,就必须使用该关键字)
{
double result = 0;
result = NumberA + NumberB;
return result;
}
}
/// <summary>
/// 减法类,继承运算类
/// </summary>
class OperationSub : Operation
{
public override double GetResult()
{
double result = 0;
result = NumberA - NumberB;
return result;
}
}
/// <summary>
/// 乘法类,继承运算类
/// </summary>
class OperationMul : Operation
{
public override double GetResult()
{
double result = 0;
result = NumberA * NumberB;
return result;
}
}
/// <summary>
/// 除法类,继承运算类
/// </summary>
class OperationDiv : Operation
{
public override double GetResult()
{
double result = 0;
if (NumberB == 0)
throw new Exception("除数不能为0。");
result = NumberA / NumberB;
return result;
}
}
/// <summary>
/// 简单运算工厂类
/// </summary>
public class OperationFactory
{
public static Operation createOperate(string operate)
{
Operation oper = null; //没有对父类进行实例化
//可以把某个派生类型的变量赋给基本类型的变量
switch (operate)
{
case "+":
oper = new OperationAdd(); //子类实例化
break;
case "-":
oper = new OperationSub();
break;
case "*":
oper = new OperationMul();
break;
case "/":
oper = new OperationDiv();
break;
}
return oper;
//相当于父类也实例化了
}
}
}
主执行方法:Program.cs
只需要输入运算符号,工厂就实例化出适合的对象,通过多态,返回父类的方法实现了计算器的结果;
不同的子类都重写了父类的GetResult()方法,子类GetResult()方法的使用也算是一种多态
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SimpleFactory
{
class Program
{
static void Main(string[] args)
{
try
{
Operation oper;
Console.Write("请选择运算符号(+、-、*、/):");
oper = OperationFactory.createOperate(Console.ReadLine()); //要先进行赋值,才能在后面对oper.NumberA进行赋值
Console.Write("请输入数字A