此处示例为一个简易计算器工厂模式的实现.
创建类库,名为CalcLib,我把计算功能全部放在这个类库中.
首先,创建一个抽象的计算器算法父类,如下:
/// <summary>
/// 计算器算法父类
/// </summary>
public abstract class Calculator
{
public Calculator()
{
}
//给子类的参数
public Calculator(double n1, double n2)
{
this.Number1 = n1;
this.Number2 = n2;
}
public double Number1 { get; set; }
public double Number2 { get; set; }
/// <summary>
/// 抽象计算方法
/// </summary>
/// <returns>result</returns>
public abstract double Compute();
}
父类创建完毕后,我们在子类来实现具体的加减乘除
加法类:
/// <summary>
/// 加法
/// </summary>
public class CalAdd:Calculator
{
public CalAdd(double n1, double n2)
:base(n1,n2)
{
}
public override double Compute()
{
return Number1 + Number2;
}
}
减法类:
/// <summary>
/// 减法
/// </summary>
public class CalSub:Calculator
{
public CalSub(double n1, double n2)
:base(n1,n2)
{
}
public override double Compute()
{
return Number1 - Number2;
}
}
乘法类:
/// <summary>
/// 乘法
/// </summary>
public class CalMul:Calculator
{
public CalMul(double n1, double n2)
:base(n1,n2)
{
}
public override double Compute()
{
return Number1 * Number2;
}
}
除法类:
/// <summary>
/// 除法
/// </summary>
public class CalDiv : Calculator
{
public CalDiv(double n1, double n2)
: base(n1, n2)
{
}
public override double Compute()
{
return Number1 / Number2;
}
}
OK,需要的计算方法都创建完毕了,现在,我们来创建主程序,这里呢我创建一个控制台程序,名为MyCalculator,然后呢在Program类中添加一个静态的计算工厂方法。
/// <summary>
/// 计算工厂
/// </summary>
/// <param name="n1">操作数1</param>
/// <param name="op">符号</param>
/// <param name="n2">操作数2</param>
/// <returns>计算结果</returns>
static Calculator Cal(double n1, string op, double n2)
{
Calculator cal = null;
switch (op)
{
case "+":
cal = new CalAdd(n1, n2);
break;
case "-":
cal = new CalSub(n1, n2);
break;
case "*":
cal = new CalMul(n1, n2);
break;
case "/":
cal = new CalDiv(n1, n2);
break;
default:
break;
}
return cal;
}
最后呢我在Main方法中添加了以下代码:
static void Main(string[] args)
{
Console.Title = "简易计算器";
Console.WindowWidth = 37;
Console.WindowHeight = 10;
Console.ForegroundColor = ConsoleColor.Green;
while (true)
{
try
{
Console.Clear();
Console.WriteLine("请输入操作数1:");
double n1 = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("请输入操作符:");
string op = Console.ReadLine();
Console.WriteLine("请输入操作数2:");
double n2 = Convert.ToDouble(Console.ReadLine());
Calculator cal = Cal(n1, op, n2);
if (cal != null)
Console.WriteLine("计算结果为:{0}", cal.Compute());
Console.WriteLine("再次按回车继续计算...");
Console.ReadLine();
}
catch { break; }
}
}
OK,一个简单的工厂模式实现就完成了,用工厂模式首先呢要有一个公用的抽象意义,然后再来使用,新功能无需更改任何代码,只需要新增一个类,基础父类,然后实现你要得功能就可以了,有点类似于浏览器和插件。