假如有個類別, 它有很多的建構函數, 對使用者來說, 會混淆何時該呼叫哪種建構函數.
假設有個線上遊戲的玩家類別, 玩家會根據它建立的時間, 有不同的活動優惠、加值優惠等屬性.
class Player
{
public Player(string name, Job job)
{
// self logic
}
public Player(string name, Job job, bool isCreatedIn2022Winter)
{
// self logic
}
public Player(string name, Job job, double paidSales)
{
// self logic
}
}
將所有的建構函數, 轉換成static的creation method, 並採用Chain Constuctors
來減少重複邏輯
class Player
{
private Player(string name, Job job) : this(name, job, false, 0)
{
// empty!
}
private Player(string name, Job job, bool isCreatedIn2022Winter, double paidSales)
{
// self logic
}
public static Player CreateNormalPlayer(string name, Job job)
{
return new Player(name, job);
}
public static Player CreateCreatedIn2022WinterPlayer(string name, Job job)
{
return new Player(name, job, true, 0);
}
public static Player CreatePaidSalesPlayer(string name, Job job, double paidSales)
{
return new Player(name, job, false, paidSales);
}
}
Player
Player
的建構函數是各自處理邏輯, 而重構採用Chain Constuctors
, 最終的建構函數只會有一個專門把參數設為自己fields.如果creation method太多, 對這類別的職責太龐大, 建議要轉換成factory.