C#中的简单工厂设计模式示例
2021-05-04 18:27
标签:简单 工厂设计 这个是用面向对象的方法来实现加,减,乘,除的计算,使用了“简单工厂的设计模式”。 using System; namespace 简单公司实现计算1 } /// return cal; public CalFather(double One,double Two) public abstract double GetResult(); } } } } 本文出自 “cary_qin的博客” 博客,请务必保留此出处http://xpqinqun.blog.51cto.com/2136/1974499 C#中的简单工厂设计模式示例 标签:简单 工厂设计 原文地址:http://xpqinqun.blog.51cto.com/2136/1974499
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("请输入第一个数字:");
double n1= Convert.ToDouble( Console.ReadLine());
Console.WriteLine("请输入第二个数字:");
double n2= Convert.ToDouble(Console.ReadLine());
Console.WriteLine("请输入一个操作符");
string oper= Console.ReadLine();
CalFather cal = Result(oper, n1, n2);
double result= cal.GetResult();
Console.WriteLine(result);
Console.ReadKey();
/// 简单工厂模式
///
/// 传入的操作符
/// 第一个运算的数字
/// 第二个运算的数字
///
public static CalFather Result(string oper,double n1,double n2)
{
CalFather cal = null;
switch (oper)
{
case "+": cal = new Add(n1, n2);
break;
case "-": cal = new Sub(n1, n2);
break;
case "*": cal = new Ride(n1, n2);
break;
case "/":cal=new Chu(n1,n2);
break;
default: Console.WriteLine("输入有误");
break;
}
}
}
///
/// 父类模型,用abstract抽象函数来实现多态
///
public abstract class CalFather
{
public double NumberOne
{
get;
set;
}
public double NumberTwo
{
get;
set;
}
{
this.NumberOne = One;
this.NumberTwo = Two;
}
}
///
/// 加法的子类
///
public class Add:CalFather
{
public Add(double one,double two):base(one,two)
{
public override double GetResult()
{
return this.NumberOne + this.NumberTwo;
}
}
///
/// 减法的子类
///
public class Sub:CalFather
{
public Sub(double one,double two):base(one,two)
{
public override double GetResult()
{
return this.NumberOne - this.NumberTwo;
}
}
///
/// 乘法的子类
///
public class Ride:CalFather
{
public Ride(double one,double two):base(one,two)
{
public override double GetResult()
{
return this.NumberOne * this.NumberTwo;
}
}
///
/// 除法的子类
///
public class Chu:CalFather
{
public Chu(double one,double two):base(one,two)
{
public override double GetResult()
{
return this.NumberOne / this.NumberTwo;
}
}
}