在工程中使用设计模式的目的是为了让代码达到复用性好,扩展性好,可维护性强三个最终目的,与此同时还需要降低类与类之间的耦合性。
工厂类C#实践
一个简单的计算类,加减乘除都继承自基类 operation
using System;
namespace Factory1
{
//Base
public class Operation
{
private double _numberA = 0;
private double _numberB = 0;
public double numberA
{
get { return _numberA;}
set { _numberA = numberA;}
}
public double numberB
{
get { return _numberB;}
set { _numberB = numberB;}
}
public virtual double GetResult()
{
double result = 0;
return result;
}
}
//add
class OperationAdd:Operation
{
public override double GetResult()
{
double result = 0;
result = numberA + numberB;
return result;
}
}
//Sub
class OperationSub:Operation
{
public override double GetResult()
{
double result = 0;
result = numberA - numberB;
return result;
}
}
//Multi
class OperationMul:Operation
{
public override double GetResult()
{
double result = 0;
result = numberA * numberB;
return result;
}
}
//Div
class OperationDiv:Operation
{
public override double GetResult()
{
double result = 0;
if(numberB==0){
throw new Exception("can not be zero!");
}
result = numberA/numberB;
return result;
}
}
public class OperationFactory{
public static Operation createOperate(string operate)
{
Operation oper = null;
switch (operate)
{
case"+":
oper = new OperationAdd();
break;
case"-":
oper = new OperationSub();
break;
case"*":
oper = new OperationMul();
break;
case"/":
oper = new OperationDiv ();
break;
}
return oper;
}
}
class MainClass
{
public static void Main (string[] args)
{
Operation a;
a = OperationFactory.createOperate("+");
a.numberA = 2;
a.numberB = 3;
double result = a.GetResult();
}
}
}