我不确定这里是否应该使用某种模式,但情况是这样的:
我有许多实现接口(interface)的具体类:
public interface IPerformAction
{
bool ShouldPerformAction();
void PerformAction();
}
我有另一个类检查输入以确定是否应该执行 ShouldPerformAction。问题在于新支票的添加相当频繁。检查类的接口(interface)定义如下:
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
}
}
现在每次添加新检查时,我都必须重构具体类以包含新检查。每个具体类将不同的属性传递给检查方法,因此不能选择具体类的子类。关于如何以更清洁的方式实现这一点有什么想法吗?
最佳答案
让我们退后一步 - 为什么首先要使用接口(interface)? IShouldPerformActionCheck
的单个实现能否在 IPerformAction
的多个实现之间共享?答案似乎是否定的,因为 ICheck 必须知道 Action 上特定于实现的属性(Property1、Property2、Property3)才能执行检查。因此,IAction 和 ICheck 之间的关系需要比 IAction 合约可以提供给 ICheck 的信息更多的信息。看起来您的 Check 类应该基于具体的实现,这些实现与它们检查的特定操作类型相耦合,例如:
abstract class CheckConcreteClass
{
abstract void Check(ConcreteClass concreteInstance);
}
关于c# - 可维护性的设计模式问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1911640/