简单工厂
代码
using System;
using System.Collections.Generic;
public class Calc
{
public virtual double DoDalc(double p1,double p2)
{
return 0;
}
}
public class Add:Calc
{
public override double DoDalc(double p1,double p2)
{
return p1+p2;
}
}
public class Minus:Calc
{
public override double DoDalc(double p1,double p2)
{
return p1-p2;
}
}
public class Multiply:Calc
{
public override double DoDalc(double p1,double p2)
{
return p1*p2;
}
}
public class Devide:Calc
{
public override double DoDalc(double p1,double p2)
{
if(p2>-0.00000000001 &&p2<0.00000000001)
{
return 0;
}
else
{
return p1/p2;
}
}
}
public class SimpleCalculator
{
public static Calc CreateCalculator(string strOperator)
{
Calc mycalc=null;
switch(strOperator)
{
case "+":
mycalc=new Add();
break;
case "-":
mycalc=new Minus();
break;
case "*":
mycalc=new Multiply();
break;
case "/":
mycalc=new Devide();
break;
default:
mycalc=new Calc();
break;
}
return mycalc;
}
}
public class MyClass
{
public static void Main()
{
Calc mycalc=SimpleCalculator.CreateCalculator("*");
double myresult=mycalc.DoDalc(1.0,20);
Console.WriteLine(myresult);
Console.ReadLine();
}
}
using System.Collections.Generic;
public class Calc
{
public virtual double DoDalc(double p1,double p2)
{
return 0;
}
}
public class Add:Calc
{
public override double DoDalc(double p1,double p2)
{
return p1+p2;
}
}
public class Minus:Calc
{
public override double DoDalc(double p1,double p2)
{
return p1-p2;
}
}
public class Multiply:Calc
{
public override double DoDalc(double p1,double p2)
{
return p1*p2;
}
}
public class Devide:Calc
{
public override double DoDalc(double p1,double p2)
{
if(p2>-0.00000000001 &&p2<0.00000000001)
{
return 0;
}
else
{
return p1/p2;
}
}
}
public class SimpleCalculator
{
public static Calc CreateCalculator(string strOperator)
{
Calc mycalc=null;
switch(strOperator)
{
case "+":
mycalc=new Add();
break;
case "-":
mycalc=new Minus();
break;
case "*":
mycalc=new Multiply();
break;
case "/":
mycalc=new Devide();
break;
default:
mycalc=new Calc();
break;
}
return mycalc;
}
}
public class MyClass
{
public static void Main()
{
Calc mycalc=SimpleCalculator.CreateCalculator("*");
double myresult=mycalc.DoDalc(1.0,20);
Console.WriteLine(myresult);
Console.ReadLine();
}
}