[设计模式] 简单工厂(Simple Factory)

Introduction

(原文出处 大话设计模式 )

Example

``````
///
/// 运算类
///
public abstract class Operation {
private double _numberA = 0;
private double _numberB = 0;

///
/// 数字A
///
public double NumberA {
get {
return _numberA;
}
set {
_numberA = value;
}
}

///
/// 数字B
///
public double NumberB {
get {
return _numberB;
}
set {
_numberB = value;
}
}

///
/// 得到运算结果
///
///
public virtual double GetResult() {
double result = 0;
return result;
}
}``````

``````
///
/// 加法类
///
public override double GetResult() {
double result = 0;
result = NumberA + NumberB;
return result;
}
}

///
/// 减法类
///
class OperationSub : Operation {
public override double GetResult() {
double result = 0;
result = NumberA - NumberB;
return result;
}
}

///
/// 乘法类
///
class OperationMul : Operation {
public override double GetResult() {
double result = 0;
result = NumberA * NumberB;
return result;
}
}

///
/// 除法类
///
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 operate) {
Operation oper = null;
switch (operate) {
case "+": {
break;
}
case "-": {
oper = new OperationSub();
break;
}
case "*": {
oper = new OperationMul();
break;
}
case "/": {
oper = new OperationDiv();
break;
}
case "sqr": {
oper = new OperationSqr();
break;
}
case "sqrt": {
oper = new OperationSqrt();
break;
}
case "+/-": {
oper = new OperationReverse();
break;
}
}

return oper;
}
}``````

``````
static void Main(string[] args) {
try {
Console.Write("请输入数字A：");
Console.Write("请选择运算符号(+、-、*、/)：");
Console.Write("请输入数字B：");
string strResult = "";

Operation oper;
oper = OperationFactory.createOperate(strOperate);
oper.NumberA = Convert.ToDouble(strNumberA);
oper.NumberB = Convert.ToDouble(strNumberB);
strResult = oper.GetResult().ToString();

Console.WriteLine("结果是：" + strResult);

}
catch (Exception ex) {
Console.WriteLine("您的输入有错：" + ex.Message);
}
}``````