设计模式之(简单工厂)(C#实现)(程杰)
接口父类的定义,把子类中公共的部分放到父类中。最大限度利用继承。。。
public class Operation
{
private int _numberA=0;
private int _numberB=0;
public int NumberA
{
get{return _numberA;}
set{_numberA=value;}
}
public int NumberB
{
get{return _numberB;}
set{_numberB=value;}
}
public virtual int GetResult()
{
int result=0;
return result;
}
}//子类1的实现表示一种产品或者说一种方式
class OperateA:Operation
{
public override int GetResult()
{
int result=0;
result=NumberA+NumberB;
return result;
}
}
//子类2实现
class OperateB:Operation
{
pulic override int GetResult()
{
int result=NumberA-NumberB;
return result;
}
}
class OperateC:Operation
{
public int GetResult()
{
int result=NumberA*NumberB;
return result;
}
}
public class OperationFactory
{
public static Operation createOperatin(string operate)
{
Operation oper=null;
swicth(operate)
{
case "add":
oper=new OperateA();
break;
case "Sub":
oper=new OperateB();
break;
case "Mull":
oper=new OperateC();
break;
}
return oper;
}
}
客户端调用:
Operation oper=OperationFactory.createOperation(texbox1.Text);
oper.NumberA=Convert.ToInt32(NumberA.Text);
oper.NumberB=Convert.ToInt32(NumberB.Text);
int result=oper.GetResult();
附录图稍后: