2012-11-05 32 views
1

我想爲網站建立一個Register類。這裏是我的使用情況 -我的設計遵循單一職責原則嗎?

  1. 用戶將註冊
  2. 提供電子郵件ID &密碼如果電子郵件ID已經存在,那麼註冊類將發送一個錯誤信息,此電子郵件在我們的系統中已存在
  3. 如果電子郵件沒有在我們的syetem存在,那麼註冊類會在發送電子郵件的用戶ID和顯示消息激活電子郵件發送至用戶 - 一個激活郵件已發送到他/ SER電子郵件

這裏的設計,我想到了

Interface IRegister 
{ 
string RegisterUser(string email, string password); 
} 

public class Register:IRegister 
{   
    public string RegisterUser(string email, string password) 
    { 
     //Call IsUserExist and SentActivationEmail method internally 
    } 

    private bool IsUserExist() 
    {    
    } 

    private void SendActivationEmail() 
    { 
    } 
} 

我不想在IRegister中提到IsUserExist和SendActivationEmail方法,這樣它仍然很簡單。現在,我可以如何強制實施註冊類的開發人員,他/她應該使用IsUserExist和SendActivationEmail方法,並執行用例中提到的所有操作。這個設計是否違反SRP原則?

+3

請記住,設計模式只是指導方針。事實上,許多設計原則是矛盾的,因爲總是存在折衷。 – Antimony

回答

2

如果您想強制開發人員使用這些方法,那麼您應該使用受保護的抽象方法而不是接口來聲明抽象類。然後定義強制執行這些方法,但是開發人員可以自由地實現它們,但是他們需要。

public abstract class Register:IRegister 
{   
    public string RegisterUser(string email, string password) 
    { 
     //Call IsUserExist and SentActivationEmail method internally 
    } 

    protected abstract bool IsUserExist(); 

    protected abstract void SendActivationEmail(); 
} 

話雖這麼說,保持與SRP原則,我會拉它的電子郵件部分伸到依賴IActivationEmailer接口。電子郵件和註冊實際上是兩種不同的行爲,應該分開保存。

public interface IActivationEmailer { 
    void SendActivationEmail(); 
} 

public abstract class Register:IRegister 
{   
    private IActivationEmailer m_emailer; 
    protected Register(IActivationEmailer emailer){ 
     // store emailer to field 
     m_emailer = emailer; 
    } 

    public string RegisterUser(string email, string password) 
    { 
     //Call IsUserExist and m_emailer.SentActivationEmail method internally 
    } 

    protected abstract bool IsUserExist(); 

} 
+0

感謝邁克的迴應。一個問題,如果我去抽象類,那麼我仍然需要IRegister接口?任何使用這個接口的好處?我也意識到SendActivationEmail和IsUserExist方法應該帶一個參數'emailID',我的不好。 –

+0

如果您公開公開抽象類,那麼您可能不需要該接口。 –

0

我同意麥克斯的答案。略有不同的辦法是應用template method,讓子類定義它們希望在登記做什麼(我不熟悉C#所以請多多包涵):

public abstract class Register:IRegister 
{   
    public string RegisterUser(string email, string password) 
    { 
     if (this.IsUserExist()) 
     { 
     //throw the error 
     } 
     else 
     { 
     this.performRegistration(); 
     this.notifyUSer(); 
     } 
    } 

    protected abstract bool IsUserExist(); 

    protected abstract notifyUSer(); 

    protected abstract performRegistration(){} 
} 

然後,麥克指出,您可以定義:

public interface IActivationEmailer { 
    void SendActivationEmail(); 
} 

public class CustomRegister 
{   
    private IActivationEmailer m_emailer; 

    public CustomRegister(IActivationEmailer emailer){ 
     // store emailer to field 
     m_emailer = emailer; 
    } 

    protected abstract bool IsUserExist(){...} 

    protected abstract notifyUSer() {this.m_emailer.SendActivationEmail();} 

    protected abstract performRegistration(){...} 
} 

所以基本上註冊類定義的步驟的註冊過程中遵循但它留下的子類來說明如何執行這些步驟。

HTH