简单工厂模式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;
}
}
}