[Design Patterns]SimpleFactoryPattern

簡單工廠模式,又稱為靜態工廠模式(Static Factory),屬於『創建型模式』。

目的

透過一個專門的類別,來創建其他類別的實體(通常繼承同一個父類別)

角色

  • 工廠(Factory):負責創建所有實體。
  • 抽象產品(AbstractProduct):一般為具體產品的父類別
  • 具體產品(ConcreteProduct):繼承抽象產品,並由工廠創建出實體

優點

  • 客戶端只需選產品,如何製造出來由工廠控制。
  • 變更與新增具體產品,不需動到客戶端。

缺點

  • 所有創建都於工廠,若無法正常使用,會影響整個系統
  • 變更與新增產品就要修改工廠,若產品多會讓工廠過於複雜,不利維護與擴展

UML

UML

實際範例:計算器

  • 抽象產品:Operation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public abstract 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 abstract double GetResult();
}
  • 具體產品: +-*/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
public class OperationAdd : Operation
{
public override double GetResult()
{
try
{
double result = 0;
result = NumberA + NumberB;
return result;
}
catch (Exception ex)
{
throw ex;
}
}
}

public class OperationSub : Operation
{
public override double GetResult()
{
try
{
double result = 0;
result = NumberA - NumberB;
return result;
}
catch (Exception ex)
{
throw ex;
}
}
}

public class OperationMul : Operation
{
public override double GetResult()
{
try
{
double result = 0;
result = NumberA * NumberB;
return result;
}
catch (Exception ex)
{
throw ex;
}
}
}

public class OperationDiv : Operation
{
public override double GetResult()
{
try
{
double result = 0;

if (NumberB.Equals(0))
throw new Exception("除數不能為0");

result = NumberA / NumberB;
return result;
}
catch (Exception ex)
{
throw ex;
}
}
}
  • 工廠
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public class OperationFactory
{
public static Operation CreateOperate(string operate)
{
try
{
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;
default:
throw new Exception("不支援此運算符號");
}

return oper;
}
catch (Exception ex)
{
throw ex;
}
}
}
  • 使用方式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Operation oper;
oper = OperationFactory.CreateOperate("+");
oper.NumberA = 1;
oper.NumberB = 2;
var addResult = oper.GetResult();

oper = OperationFactory.CreateOperate("-");
oper.NumberA = 1;
oper.NumberB = 2;
var subResult = oper.GetResult();

oper = OperationFactory.CreateOperate("*");
oper.NumberA = 1;
oper.NumberB = 2;
var mulResult = oper.GetResult();

oper = OperationFactory.CreateOperate("/");
oper.NumberA = 1;
oper.NumberB = 2;
var divResult = oper.GetResult();
-------------The End-------------