【问题标题】:Adding a conditional logic without violating SOLID principles C#添加条件逻辑而不违反 SOLID 原则 C#
【发布时间】:2016-01-21 09:28:10
【问题描述】:

我有如下接口和实现。 如果一个数字可以被除数整除,它将显示名为“可除数”的内容。 现在新的增强功能出现在我需要根据时间更改文本的地方。 如果数字是可整除的,并且时间是 12:00 PM,则显示“Divisible ***”。如果时间不是“12:PM”,则显示旧值,即“Divisible”。 我知道可以做到,但条件是我们不应该违反SOLID原则。我所做的设计是否错误?请提出建议。

public interface IRule
{
    string GetResult(int number);
}

public class DivisibleRule : IRule
{

    private readonly int divisor;


    private readonly string contentToDisplay;


    private readonly string replacementContent;


    public DivisibleRule(int divisor, string contentToDisplay)
    {
        this.divisor = divisor;
        this.contentToDisplay = contentToDisplay;
    }

    /// <summary>
    /// Gets the result.
    /// </summary>
    /// <param name="input">The input.</param>
    /// <returns>Returns the content if divisible.</returns>
    public string GetResult(int input)
    {
        return input % this.divisor == 0
             ?  this.contentToDisplay
            : string.Empty;
    }
}

【问题讨论】:

    标签: c# architecture solid-principles


    【解决方案1】:

    如果您想在不修改现有代码的情况下添加此功能(这基本上是Open/closed principle 的含义),那么您可以添加一个decorator,它将新的条件逻辑应用于从现有DivisibleRule 返回的结果.然后在任何合适的地方,你都可以使用用你的装饰器装饰的DivisibleRule

    这个装饰器看起来像这样:

    public class RuleTimeDecorator : IRule
    {
        private readonly IRule _decoratedRule;
    
        public RuleTimeDecorator(IRule decoratedRule)
        {
            _decoratedRule = decoratedRule;
        }
    
        public string GetResult(int input)
        {
            var result = _decoratedRule.GetResult(input);
    
            return IsMidnight()? $"{result} ***" : result;
        }
    
        private bool IsMidnight() => //here goes the code to check if current time meets criteria 
    }
    

    很好的是,这个装饰器可以用来装饰IRule 的任何其他植入(只要它在您的域中有意义)。

    顺便说一句,我正在使用一些 C#6 功能,例如字符串插值和表达式主体成员,但这不是必需的。

    【讨论】:

      猜你喜欢
      • 2013-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-29
      • 1970-01-01
      • 1970-01-01
      • 2016-12-29
      • 1970-01-01
      • 2022-10-06
      相关资源
      最近更新 更多