結合策略 與 簡單工廠模式

結合策略 與 簡單工廠模式

結合策略 與 簡單工廠模式

結合策略 與 簡單工廠模式

https://davidchenblog.com/posts/9ad0ae13/#more
單純只用策略模式的話,會發現必須在client判斷使用哪一種演算法。

但結合策略與簡單工廠模式,就可以在class的建構子傳入要使用哪一種演算法。

Refactor CashContext class

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
class CashContext
{
CashSuper cs = null;
public CashContext(String type)
{
switch(type)
{
case "正常收費":
CashNormal cs0 = new CashNormal();
cs = cs0;
break;
case "滿300送100":
CashReturn cr1 = new CashReturn("300","100");
cs = cr1;
break;
case "打8折":
CashRebate cr2 = new CashRebate("0.8");
cs = cr2;
break;
}
}

public double GetResult(double money)
{
return cs.acceptCash(money);
}
}

簡單工廠模式
CashSuper csuper = new CashFactory.createCashAccept(type);
…=csuper.GetResult(…);

結合策略與簡單工廠模式
CashContext csuper = new CashContext(type);
…=csuper.GetResult(…);

簡單工廠模式需讓client使用到兩個class(CashSuper、CashFactory)
結合策略與簡單工廠模式只需要用到CashContext
耦合更低!