簡單工廠模式c#
簡單工廠模式c#上簡單例子
namespace simplefactory
{
public partial class Form1 : Form
{
private void button1_Click(object sender, EventArgs e)//用戶層次
{
Operation operation = OperationFactory.createOperate(this.cbbOperation.SelectedIndex);//連接到簡單工廠獲取算法
operation.NumberA = Convert.ToDouble(this.txtNumberOne.Text);//對簡單工廠得來的算法進行賦值
operation.NumberB = Convert.ToDouble(this.txtNumberTwo.Text);
this.txtResult.Text = operation.getResult().ToString();//獲取算法結果
}
}
class OperationFactory//簡單工廠層次
{
public static Operation createOperate(int operate)//工廠內分加法和減法兩種
{
Operation oper = null;
switch (operate)
{
case 0:
{
oper = new OperationAdd();//加法
break;
}
case 1:
{
oper = new OperationSub();//減法
break;
}
}
return oper;
}
}
public abstract class Operation//對加減法算法時行抽象,以方便統一賦值NumberA、NumberB及計算結果getResult()
{
public double NumberA { get; set; }
public double NumberB { get; set; }
public abstract double getResult();
}
class OperationAdd : Operation//加法算法繼承抽象算法
{
public override double getResult()
{
return NumberA + NumberB;
}
}
class OperationSub : Operation//減法算法繼承抽象算法
{
public override double getResult()
{
return NumberA - NumberB;
}
}
}