2016-01-21 64 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功能,如字符串插值和表達體成員,但這不是必需的。

相關問題