using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Operation oper;
oper = OperationFactory.createOperate("+");
oper.NumberA = 1;
oper.NumberB = 2;
double result = oper.GetResult();
}
}
public class Operation
{
private double _numberA;
private double _numberB;
public double NumberA
{
get { return _numberA; }
set { _numberA = value; }
}
public double NumberB
{
get { return _numberB; }
set { _numberB = value; }
}
public virtual double GetResult ()
{
double result=0;
return result;
}
}
public class OperationAdd : Operation
{
public override double GetResult()
{
double result = 0;
result = NumberA + NumberB;
return result;
}
}
public class OperationSub : Operation
{
public override double GetResult()
{
double result = 0;
result = NumberA - NumberB;
return result;
}
}
public class OperationMul : Operation
{
public override double GetResult()
{
double result = 0;
result = NumberA * NumberB;
return result;
}
}
public class OperationDiv : Operation
{
public override double GetResult()
{
double result = 0;
if (NumberB == 0)
throw new Exception("除数不能为0。");
result=NumberA/NumberB;
return result;
}
}
public class OperationFactory
{
public static Operation createOperate(string operation)
{
Operation oper=null;
switch(operation)
{
case "+":
oper=new OperationAdd();
break;
case "-":
oper=new OperationSub();
break;
case "*":
oper=new OperationMul();
break;
case "/":
oper=new OperationDiv();
break;
}
return oper;
}
}
}
工厂 OperationFactory:
方法createOperation是Operation类型,定义了一个Operation类型的变量oper,
根据operation:"+"、"-"、"*"、"/",实例化(继承父类Operation)OperationAdd、OperationSub、OperationMul、OperationDiv
oper=new OperationAdd();
客户端:
定义Operation类型的变量oper;
oper = OperationFactory.createOperate("+");
决定oper实例化OperationAdd,
double result = oper.GetResult();
直接调OperationAdd的GetResult方法:
public class OperationAdd : Operation
{
public override double GetResult()
{
double result = 0;
result = NumberA + NumberB;
return result;
}
}