2016-01-21 59 views
2

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

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; 
    } 
} 

回答

2

如果您要在不修改现有的代码(这基本上是什么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任何其他植入(只要它使Sens在您的域名)。

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

相关问题