请用C#面向对象语言实现一个计算器控制台程序,要求输入两个数和运算符号,得到结果。

面向过程:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PatternTest
{
class Program
{
static void Main(string[] args)
{
Console.Write("请输入数字A: ");
string A = Console.ReadLine();

Console.Write("请选择运算符号(+、-、*、/):");
string B = Console.ReadLine();

Console.Write("请输入数字B: ");
string C = Console.ReadLine();

string D = "";
if (B == "+")
D = Convert.ToString(Convert.ToDouble(A) + Convert.ToDouble(C));
if (B == "-")
D = Convert.ToString(Convert.ToDouble(A) - Convert.ToDouble(C));
if (B == "*")
D = Convert.ToString(Convert.ToDouble(A) * Convert.ToDouble(C));
if (B == "/")
D = Convert.ToString(Convert.ToDouble(A) / Convert.ToDouble(C));

Console.WriteLine("结果是: " + D);

测试结果

请输入数字A: 1
请选择运算符号(+、-、*、/):+
请输入数字B: 2
结果是: 3
请按任意键继续. . .

缺陷:

1 对象命名不规范
2 没有判断除数不能为0的情况
3 面向过程, if 判断分支会多做无效判断

简单工厂

类图

C#设计模式之:简单工厂_C#

代码

// Operation.cs
namespace PatternTest.SampleFactory
public class Operation
private double _numberA = 0;
private double _numberB = 0;

public double NumberA { get => _numberA; set => _numberA = value; }
public double NumberB { get => _numberB; set => _numberB = value; }

public virtual double GetResult()
{
double result = 0;
return result;
}
}
}

// OperationAdd.cs
namespace PatternTest.SampleFactory
class OperationAdd : Operation
public override double GetResult()
{
double result = 0;
result = NumberA + NumberB;
return result;
}
}
}

// OperationSub.cs
namespace PatternTest.SampleFactory
class OperationSub : Operation
public override double GetResult()
{
double result = 0;
result = NumberA - NumberB;
return result;
}
}
}

// OperationMul.cs
namespace PatternTest.SampleFactory
class OperationMul : Operation
public override double GetResult()
{
double result = 0;
result = NumberA * NumberB;
return result;
}
}
}

// OperationDiv.cs
namespace PatternTest.SampleFactory
class OperationDiv : Operation
public override double GetResult()
{
double result = 0;
if (NumberB == 0)
throw new Exception("除数不能为0");
result = NumberA / NumberB;
return result;
}
}
}

// OperationFactory.cs
namespace PatternTest.SampleFactory
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;
}
}
}

// test
namespace PatternTest.SampleFactory
class Program
Operation oper;
oper = OperationFactory.createOperate("+");
oper.NumberA = 1;
oper.NumberB = 2;
double result = oper.GetResult();
Console.WriteLine("结果是: "

优点:

如果有一天要修改加法运算,只要修改OperationAdd 即可
如果有一天要添加新的复杂运算,只要添加相应的运算子类,然后在运算类工厂的switch分支中增加其分支