原理
這種類(lèi)型的設(shè)計(jì)模式屬于創(chuàng)建型模式,它提供了一種創(chuàng)建對(duì)象的最佳方式。
在工廠(chǎng)模式中,我們?cè)趧?chuàng)建對(duì)象時(shí)不會(huì)對(duì)客戶(hù)端暴露創(chuàng)建邏輯,并且是通過(guò)使用一個(gè)共同的接口來(lái)指向新創(chuàng)建的對(duì)象。
意圖
定義一個(gè)創(chuàng)建對(duì)象的接口,讓其子類(lèi)自己決定實(shí)例化哪一個(gè)工廠(chǎng)類(lèi),工廠(chǎng)模式使其創(chuàng)建過(guò)程延遲到子類(lèi)進(jìn)行。
主要解決
主要解決接口選擇的問(wèn)題。
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 簡(jiǎn)單工廠(chǎng)模式
{
class Program
{
static void Main(string[] args)
{
Operation oper;
oper = OperationFactory.createOperate("+");
oper.NumberA = 1;
oper.NumberB = 2;
double result = oper.GetResult();
Console.Write("result: " + result);
Console.ReadKey();
}
}
}
Operation.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 簡(jiǎn)單工廠(chǎng)模式
{
//簡(jiǎn)單工廠(chǎng)類(lèi)
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;
}
}
//運(yùn)算類(lèi)
class Operation
{
private double _numberA = 0;
private double _numberB = 0;
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;
}
}
//加法類(lèi)
class OperationAdd : Operation
{
public override double GetResult()
{
double result = 0;
result = NumberA + NumberB;
return result;
}
}
//減法類(lèi)
class OperationSub : Operation
{
public override double GetResult()
{
double result = 0;
result = NumberA - NumberB;
return result;
}
}
//乘法類(lèi)
class OperationMul : Operation
{
public override double GetResult()
{
double result = 0;
result = NumberA * NumberB;
return result;
}
}
//除法類(lèi)
class OperationDiv : Operation
{
public override double GetResult()
{
double result = 0;
if (NumberB == 0) {
throw new Exception("除數(shù)不能為0.");
}
result = NumberA / NumberB;
return result;
}
}
}