本文实例讲述了C#基于简单工厂模式实现的计算器功能。分享给大家供大家参考,具体如下:
子类拥有父类除私有之外的所有属性字段和方法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 工厂方法实现计算器
{
///
/// 计算器类(抽象类,由子类重写)
///
public abstract class Calculator
{
public double Number1 { get; set; }
public double Number2 { get; set; }
public Calculator() { }
public Calculator(double a, double b)
{
this.Number1=a;
this.Number2=b;
}
///
/// 计算
///
///
public abstract double jsuan();
}
///
/// 加法类
///
public class jiafaDll:Calculator //子类拥有父类除私有之外的所有属性字段和方法
{
public jiafaDll() { }
public jiafaDll(double a, double b)
: base(a, b) //调用父类带两个参数的构造函数,来初始化Number1 和Number2 (注意:因为jianfaDll类继承了Calculator,所以jianfaDll类是有Number1,和Number2两个属性的)
{ }
///
/// 重写父类的jsuan方法
///
///
public override double jsuan()
{
return Number1 + Number2;
}
}
///
/// 减法类
///
public class jianfaDll : Calculator
{
public jianfaDll()
{ }
public jianfaDll(double a, double b)
: base(a, b)
{ }
public override double jsuan()
{
return Number1 - Number2;
}
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("请输入第一个数");
double number1 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("请输入一个操作符");
string caozuofu = Console.ReadLine();
Console.WriteLine("请输入第二个数");
double number2 = Convert.ToDouble(Console.ReadLine());
Calculator c=null;
switch (caozuofu)
{
case "+":
c = new jiafaDll(number1, number2);
break;
case "-":
c = new jianfaDll(number1, number2);
break;
}
double i= c.jsuan();
Console.WriteLine(i);
Console.ReadKey();
}
}
}
PS:这里再为大家推荐几款计算工具供大家进一步参考借鉴:
希望本文所述对大家C#程序设计有所帮助。