# 设计模式(1):简单工厂模式

Class Diagram： ![ClassView.gif][2]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;</p>

namespace LazyCourse
{
///

/// 计算类
///

</span>
public abstract 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; }
}
///

/// 返回计算结果
///

</span>
/// result
public virtual double GetResult()
{
double result = ;
return result;
}
}
///

/// 加法类
///

</span>
{
public override double GetResult()
{
double result = ;
result = NumberA + NumberB;
return result;
}
}
///

/// 减法类
///

</span>
class OperationSub : Operation
{
public override double GetResult()
{
double result = ;
result = NumberA - NumberB;
return result;
}
}
///

/// 乘法类
///

</span>
class OperationMul : Operation
{
public override double GetResult()
{
double result = ;
result = NumberA * NumberB;
return result;
}
}
///

/// 除法类
///

</span>
class OperationDiv : Operation
{
public override double GetResult()
{
double result = ;
if (NumberB == )
{
throw new Exception("除数不能为0");
}
result = NumberA / NumberB;
return result;
}
}
}</div>

OperationFactory

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;</p>

namespace LazyCourse
{
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;
}
return oper;
}
}
}</div>

Program

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;</p>

namespace LazyCourse
{
class Program
{
static void Main(string[] args)
{
Operation oper;
oper = OperationFactory.createOperate("+");
oper.NumberA = 100;
oper.NumberB = 120;
Console.WriteLine(oper.GetResult());
}
}
}</div>