我有一个我想要能够处理的“规则”的概念。因此,我创建了下面的界面:
public interface IRule<T>
{
Boolean IsSatisfiedBy(T value);
String GetViolationMessage(T value);
}
我计划创建一系列“规则”类来表示系统当前支持的各种规则,例如:
public class MatchesPatternRule : IRule<String>
{
private readonly Regex _regex;
private readonly String _pattern;
public MatchesPatternRule(String pattern)
{
Verify.IsFalse(String.IsNullOrWhiteSpace(pattern));
_regex = new Regex(pattern);
_pattern = pattern;
}
public Boolean IsSatisfiedBy(String value)
{
return _regex.IsMatch(value);
}
public String GetViolationMessage(String value)
{
return String.Format(RuleMessage.MatchesPatternViolation, _pattern, value);
}
}
然后通过各种扩展方法使用这些规则,例如:
public static ValidationContext<String> MatchesPattern(this ValidationContext<String> context, String pattern)
{
context.AddRule(new MatchesPatternRule(pattern));
return context;
}
但是,我目前有20多个规则的计划,MatchesPatternRule类可以通过将扩展方法编写为:
public static ValidationContext<String> MatchesPattern(this ValidationContext<String> context, String pattern)
where T : IComparable
{
Verify.IsFalse(String.IsNullOrWhiteSpace(pattern));
Regex regex = new Regex(pattern);
context.AddRule(value => regex.IsMatch(value), value => String.Format(RuleMessage.MatchesPatternViolation, _pattern, value));
return context;
}
好奇什么方法更好,为什么?两者都很容易被证明,最终达到最终结果。任何见解都将受到极大的赞赏!
更新
根据汤姆的反馈,我认为我选择了中间立场。我将创建一个静态类来保存每个“规则”的扩展方法。这将确保任何给定的规则都很容易找到,并将保持代码的有序性,同时也减少了代码的总量。
public static class MatchesPatternRule
{
public static ValidationContext<String> MatchesPattern(this ValidationContext<String> context, String pattern)
{
return MatchesPattern<T>(context, pattern, pattern, RegexOptions.None);
}
public static ValidationContext<String> MatchesPattern(this ValidationContext<String> context, String pattern, String friendlyPattern)
{
return MatchesPattern<T>(context, pattern, friendlyPattern, RegexOptions.None);
}
public static ValidationContext<String> MatchesPattern(this ValidationContext<String> context, String pattern, RegexOptions options)
{
return MatchesPattern<T>(context, pattern, pattern, options);
}
public static ValidationContext<String> MatchesPattern(this ValidationContext<String> context, String pattern, String friendlyPattern, RegexOptions options)
{
Verify.IsFalse(String.IsNullOrWhiteSpace(pattern));
Regex regex = new Regex(pattern);
context.AddRule(value => regex.IsMatch(value), value => String.Format(RuleMessage.MatchesPatternViolation, _pattern, value));
return context;
}
}