也许您正在寻找责任链模式?
假设您必须计算奖金并且您使用这样的东西
public double GetBonusRate(int workingDays, int numberOfSales)
{
if(numberOfSales > 20)
{
return 1.5;
}
if(workingDays >= 20 && numberOfSales > 10)
{
return 1.2;
}
if(numberOfSales > 5)
{
return 1.0;
}
if(workingDays > 10)
{
return 0.1;
}
return 0;
}
您期望条件的数量会增加,并且您意识到在错误的位置添加新条件会导致错误。
责任链为您提供了另一种方法。
var chain = new PerfectBonusRate();
chain.RegisterNext(new GoodBonusRate())
.RegisterNext(new StandartBonusRate())
.RegisterNext(new LazyBonusRate())
.RegisterNext(new NoBonusRate());
var bonusRate = chain.GetBonusRate(10, 20);
执行
abstract class ChainElement
{
ChainElement _next;
public ChainElement RegisterNext(ChainElement next)
{
_next = next;
return next;
}
public double GetBonusRate(int workingDays, int numberOfSales)
{
if(IsMatched(workingDays, numberOfSales))
{
return GetBonusValue();
}
return _next.GetBonusRate(workingDays, numberOfSales);
}
protected abstract bool IsMatched(int workingDays, int numberOfSales);
protected abstract int GetBonusValue();
}
class PerfectBonusRate : ChainElement
{
protected override bool IsMatched(int workingDays, int numberOfSales)
{
return numberOfSales > 20;
}
protected override double GetBonusValue()
{
return 1.5;
}
}
class GoodBonusRate : ChainElement
{
protected override bool IsMatched(int workingDays, int numberOfSales)
{
return workingDays >= 20 && numberOfSales > 10;
}
protected override double GetBonusValue()
{
return 1.2;
}
}
//and the same for StandartBonusRate, LazyBonusRate...
class NoBonusRate : ChainElement
{
protected override bool IsMatched(int workingDays, int numberOfSales)
{
return true;
}
protected override double GetBonusValue()
{
return 0.0;
}
}