[Design Pattern] 策略模式(Strategy)
雖然利用簡單模式,可以把所有不同的計算分式全部拆開,不過這樣其實還是不夠好:因為當計算所需條件變化的時候,這樣你就必需同步修改Factory;所以我們可以再細一步分解,除了連同計算方式、計算所需條件全部封裝起來,這樣子可以再減少程式的耦合性。(例如:正品期間還會依照是否為假日給折扣~)
所以把前面計算折扣的程式小小的調整一下:
/// 折扣期間計價
/// </summary>
class SaleCalulator : Calculator
{
public SaleCalulator()
{
}
public override decimal Count(int money)
{
return Convert.ToDecimal(money * 0.8);
}
}
/// 正品期間計價
/// </summary>
class GeneralCalulator : Calculator
{
private bool _holiday;
public GeneralCalulator(bool holiday)
{
_holiday = holiday;
}
public override decimal Count(int money)
{
if (!_holiday)
return money * (decimal)0.9;
else
return money;
}
}
{
private Calculator _c;
public CalculatorContext(Calculator c)
{
_c = c;
}
public decimal Count(int money)
{
return _c.Count(money);
}
}
{
Console.Write("請輸入日期:");
string date = Console.ReadLine();
Console.Write("請輸入金額:");
string money = Console.ReadLine();
CalculatorContext c;
DateTime dt = Convert.ToDateTime(date);
switch (dt.Month)
{
case 7:
case 8:
case 9:
c = new CalculatorContext(new SaleCalulator());
break;
default:
c = new CalculatorContext(new GeneralCalulator(dt.DayOfWeek == DayOfWeek.Sunday));
break;
}
Console.WriteLine("應付金額:" + c.Count(Convert.ToInt32(money)));
Console.ReadKey();
}
Dotblogs 的標籤:Design Pattern