工厂类,求如何实现参数的不同问题,简单说就是生产需要的原材料会不一样的,怎么传原材料,用个params,然后下面判断?
class Factory
{
public static ICalculate Create(string oper,params int[]nums)
{
switch (oper)
{
case "+":return new Add()
default:
}
}
} 作者: 佘显郡 时间: 2013-10-29 16:17
这个问题都没人回答,表示很蛋疼,不过还好自己已经解决了作者: 黑飞马 时间: 2013-10-29 16:38
对于 单目、双目、多目 你可以使用策略工厂模式,对策略类进行实例化,由于代码太多,只写一部分,如下:
//这是对 单目、双目、多目的策略
public class taskFactory
{
private static OperaterTask ot = null;
public static OperaterTask getTaskType(string str) //str 为表示单目、双目、多目
{
switch (str)
{
case "single":
{
ot = new OperaterTaskSingle();
break;
}
case "double":
{
ot = new OperaterTaskDouble();
break;
}
case "mul":
{
ot = new OperaterTaskMulti();
break;
}
}
return ot;
}
}
//这是双目的策略,其他类似
public class OperaterTaskDouble:OperaterTask
{
public bool isNew = false;
public override double getTaskResult(string str, double num)
{
if (op ==null)
{
op = new OperaterFactory().getOperater(str);
this.op.OpA = num;
return num;
}
else
{
this.op.OpB = num;
double stmp = op.getResult();
op = new OperaterFactory().getOperater(str);
this.op.OpA = stmp;
this.isNew = true;
return stmp;
}
}
}
//这个就是你说的封装所有运算符为类
public class OperaterFactory
{
public Operater getOperater(string str)
{
Operater op = null;
switch (str)
{
case "+":
{
op = new OperaterAdd();
return op;
}
case "-":
{
op = new OperaterSub();
return op;
}
case "*":
{
op = new OperaterMul();
return op;
}
case "/":
{
op = new OperaterDiv();
return op;
}
case "Pow"://如2的3次方
{
op = new OperaterSqrt();
return op;
}
case "1/x":
{
op = new OperaterDao();
return op;
}
case "mod":
{
op = new OperaterYu();
return op;
}
case "AD":
{
op = new OperaterAD();
return op;
}
case "Sqrt": //开方
{
op = new OperaterPow();
return op;
}
case "x^2": //平方
{
op = new OperaterPf();
return op;
}
default:
{
return op = null;
}
}
}
}