【发布时间】:2023-04-06 22:37:02
【问题描述】:
我不确定这里是否应该使用某种模式,但情况如下:
我有许多实现接口的具体类:
public interface IPerformAction
{
bool ShouldPerformAction();
void PerformAction();
}
我有另一个类检查输入以确定是否应该执行 ShouldPerformAction。问题在于,新检查的添加相当频繁。检查类的接口定义如下:
public interface IShouldPerformActionChecker
{
bool CheckA(string a);
bool CheckB(string b);
bool CheckC(int c);
// etc...
}
最后,我目前让具体类使用特定于该具体类的数据调用每个检查器方法:
public class ConcreteClass : IPerformAction
{
public IShouldPerformActionCheck ShouldPerformActionChecker { get; set; }
public string Property1 { get; set; }
public string Property2 { get; set; }
public int Property3 { get; set; }
public bool ShouldPerformAction()
{
return
ShouldPerformActionChecker.CheckA(this.Property1) ||
ShouldPerformActionChecker.CheckB(this.Property2) ||
ShouldPerformActionChecker.CheckC(this.Property3);
}
public void PerformAction()
{
// do something class specific
}
}
现在每次添加新检查时,我都必须重构具体类以包含新检查。每个具体类将不同的属性传递给检查方法,因此子类化具体类不是一种选择。关于如何以更清洁的方式实现这一点的任何想法?
【问题讨论】:
-
我个人认为您当前的方法非常干净。我们在谈论多少个具体的类?随着新检查的出现,调整必要的具体类真的很难吗?我认为不管你如何削减它,你最终还是会得到一些你必须调整的具体课程。避免这种情况的唯一方法是在具体类使用的某处执行“CheckAll()”样式函数。不过总体而言,我认为无需调整带来的性能提升不会超过泥浆因素。
标签: c# design-patterns