Tight coupling的說明
Loose coupling的說明
假設有個員工類別, 要計算當年年終的薪水:
public class Employee
{
public decimal CalculateYearEndSalary(decimal baseSalary, int seniority)
{
decimal bonus =
BonusCalculator.CalculateBonus(baseSalary, seniority);
return baseSalary + bonus;
}
}
public class BonusCalculator
{
public static decimal CalculateBonus(decimal baseSalary, int seniority)
{
if (seniority >= 5)
{
return baseSalary * 3;
}
else
{
return baseSalary * 1;
}
}
}
以上述程式碼, Employee與BonusCalculator是緊耦合. 因為Employee直接呼叫BonusCalculator的CalculateBonus函數來計算分紅.
回顧前面提到的缺點:
public interface IBonusCalculator
{
decimal CalculateBonus(decimal baseSalary, int seniority);
}
public class Employee
{
private readonly IBonusCalculator bonusCalculator;
public Employee(IBonusCalculator bonusCalculator)
{
this.bonusCalculator = bonusCalculator;
}
public decimal CalculateYearEndSalary(decimal baseSalary, int seniority)
{
decimal bonus =
bonusCalculator.CalculateBonus(baseSalary, seniority);
return baseSalary + bonus;
}
}
public class SeniorityBonusCalculator : IBonusCalculator
{
public decimal CalculateBonus(decimal baseSalary, int seniority)
{
if (seniority >= 5)
{
return baseSalary * 3;
}
else
{
return baseSalary * 1;
}
}
}