2011-08-07 233 views
2

是正常的,在我下面的代碼使用默認的策略,如:默認策略。策略模式C#

public abstract class ClContext 
{ 
    protected sealed class InitialAlgorithm : IClAlgorithm 
    { 
     public void Initialize() 
     { 
      return; 
     } 
     public void Execute() 
     { 
      return; 
     } 
     public Byte[] Result 
     { 
      get { return new Byte[1]{0}; } 
     } 
    } 
    protected IClAlgorithm algorithm; 

    protected ClContext(IClAlgorithm algorithm = null) 
    { 
     this.algorithm = algorithm ?? new ClContext.InitialAlgorithm(); 
    } 

    public void Execute() 
    { 
     this.algorithm.Execute(); 
    } 
} 

,並且它也很正常提供自動實現的屬性,如:

public IClAlgorithm Algorithm 
{ 
    get; 
    set; 
} 

我只是好奇從設計的角度來看它是可以接受的。

謝謝!

+0

我使用'Initialize()'只是爲了說明,但謝謝! – lexeme

回答

5

我無法想象這種設計實際上會有用的場景 - 您的課程取決於,該策略通過其構造函數傳入並可能稍後通過屬性設置器進行更改。不傳遞依賴關係不應該讓調用者創建你的類的一個實例。

如果應該只是提供一個「默認」策略,那麼即使這樣做,我也不會將它們綁定在一起,而是有一個工廠方法用該策略創建您的類。