C#中的簡單工廠設計模式示例
這個是用面向對象的方法來實現加,減,乘,除的計算,使用了“簡單工廠的設計模式”。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 簡單公司實現計算1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("請輸入第一個數字:");
double n1= Convert.ToDouble( Console.ReadLine());
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();
}
/// <summary>
/// 簡單工廠模式
/// </summary>
/// <param name="oper">傳入的操作符</param>
/// <param name="n1">第一個運算的數字</param>
/// <param name="n2">第二個運算的數字</param>
/// <returns></returns>
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;
}
return cal;
}
}
/// <summary>
/// 父類模型,用abstract抽象函數來實現多態
/// </summary>
public abstract class CalFather
{
public double NumberOne
{
get;
set;
}
public double NumberTwo
{
get;
set;
}
public CalFather(double One,double Two)
{
this.NumberOne = One;
this.NumberTwo = Two;
}
public abstract double GetResult();
}
/// <summary>
/// 加法的子類
/// </summary>
public class Add:CalFather
{
public Add(double one,double two):base(one,two)
{
}
public override double GetResult()
{
return this.NumberOne + this.NumberTwo;
}
}
/// <summary>
/// 減法的子類
/// </summary>
public class Sub:CalFather
{
public Sub(double one,double two):base(one,two)
{
}
public override double GetResult()
{
return this.NumberOne - this.NumberTwo;
}
}
/// <summary>
/// 乘法的子類
/// </summary>
public class Ride:CalFather
{
public Ride(double one,double two):base(one,two)
{
}
public override double GetResult()
{
return this.NumberOne * this.NumberTwo;
}
}
/// <summary>
/// 除法的子類
/// </summary>
public class Chu:CalFather
{
public Chu(double one,double two):base(one,two)
{
}
public override double GetResult()
{
return this.NumberOne / this.NumberTwo;
}
}
}
本文出自 “cary_qin的博客” 博客,請務必保留此出處http://xpqinqun.blog.51cto.com/2136/1974499
C#中的簡單工廠設計模式示例