设计模式 之 简单工厂模式
1〉创建抽象类:
2〉各业务类继承抽象类,重写抽象类业务方法;
3〉业务工厂类根据传的业务类型,反回相应的各业务类对象;
4>客户端根据反回相应的各业务类对象赋值,调用相应的方法,反回值.
例如:计算器:输入两个数,一个运算符,反回结果
1〉创建抽象类:
class Operation
{
public double NumberA{get;set;}
public double NumberB{get;set;}
public viratul double GetResult()
{
double result=0;
return result;
}
}
2〉各业务类:
class OperationAdd:Operation
{
public ovrried double GetResult()
{
double result=0;
result=NumberA + NumberB;
return result;
}
}
class OperationSub:Operation
{
public ovrried double GetResult()
{
double result=0;
result=NumberA - NumberB;
return result;
}
}
3〉业务工厂类
class OperationFactory
{
public viratul Operation CreateOperation(string operation)
{
Operation oper=null;
switch(operation)
{
case"+":
{
oper=new OperationAdd();
break;
}
case"-":
{
oper=new OperationSub();
break;
}
}
return oper;
}
}
4>客户端
Operation oper=null;
oper=new OperationFactory("+");
oper.NumberA=1;
oper.NumberB=2;
double result= oper.GetResult();
Console.Write("result is "+result);