我有一个巨大的 switch/case 语句,我想用策略模式替换它。每个语句都有很大的代码执行特定的逻辑。有没有人有在这种情况下使用该模式的好例子,或者你有任何其他好的解决方案?
到目前为止我的解决方案
class Context
{
private readonly List<CalculationUnit> _calculationsUnits;
public Context()
{
_calculationsUnits = new List<CalculationUnit>()
{
new CalculationUnitA("calc1"),
new CalculationUnitB("calc2"),
new CalculationUnitC("calc2")
};
}
public int Calculate(string name)
{
return (from c in _calculationsUnits where c.Name.Equals(name) select c.Calculate()).FirstOrDefault();
}
}
class CalculationUnit
{
public string Name { get; private set; }
public CalculationUnit(string name)
{
Name = name;
}
public virtual int Calculate()
{
return 0;
}
}
class CalculationUnitA : CalculationUnit
{
public CalculationUnitA(string name) : base(name) { }
public override int Calculate()
{
//calculations logic A
}
}
class CalculationUnitB : CalculationUnit
{
public CalculationUnitB(string name) : base(name) { }
public override int Calculate()
{
//calculations logic A
}
}
class CalculationUnitC : CalculationUnit
{
public CalculationUnitC(string name) : base(name) { }
public override int Calculate()
{
//calculations logic A
}
}
但是我最终会得到 50 个类来实现每个逻辑......
谢谢