2012-06-29 47 views
1

我試圖進入編碼到接口而不是實現的習慣,雖然在大多數情況下,我可以看到有幾個原因我奮鬥。編程接口不實施混淆

拿這個非常簡單的例子:

public interface IAuditLog 
{ 
    void AddLog(string log); 
} 

public class AuditLog : IAuditLog 
{ 
    public void AddLog(string log) 
    { 
     //implementation 
    } 
} 

要調用的審計日誌類:

public partial class AuditLogPage : System.Web.UI.Page 
{ 
    protected void btnAddLog_Click(object sender, EventArgs e) 
    { 
     IAuditLog objAuditLog = new AuditLog(); 
     objAuditLog.AddLog("test log"); 
    } 
} 

我還是要用審計日誌實例的時候,有什麼意義呢?如果AddLog方法簽名發生變化,我仍然需要瀏覽所有使用它的頁面並修改代碼。我錯過了這一點嗎?

感謝您提前提供任何幫助, Wilky。

回答

4

讓我們想象一下,有有兩個審計日誌類

class AuditLogToDatabase : IAuditLog // writes to database 

而另一個

class AuditLogToFile : IAuditLog // writes to file 

protected void btnAddLog_Click(object sender, EventArgs e) 
{ 
    IAuditLog objAuditLog = AuditLogFactory.GetAuditLog(); 
    objAuditLog.AddLog("test log"); 
} 

現在你可以根據運行一些配置注入任何類時間不改變實際實施

+1

您可能需要將工廠添加到解決方案中... –

+0

感謝Asif。非常有意義。 – Wilky

3

這並不一定意味着您必須實際使用C#interface。 OOP術語中的接口是API公開可見的外觀。這是一個合同,應該指定外部可見的操作結果。在表面之下究竟如何工作應該是無關緊要的,以便您可以隨時更換實施。

當然,在這方面,interface是一種能夠使用不同實現的方法,但抽象基類甚至是其他派生的非抽象類也是如此。

但更多的是你的問題的確切點:當然,當實例化一個類時,它的類型必須是已知的,但你不一定要在那裏創建類實例。您可以從外部設置IAuditLog,或者通過工廠班級等獲得該代碼,在代碼中的確切位置,您將得到的確切類型(除與IAuditLog兼容外)。

+0

+1:questi的本質唯一的答案 – Vlad

5

在示例中,如果您使用DatabaseAuditLogger()EventLogAuditLogger()切換出FileAuditLogger(),則可以切換實現而不必重寫代碼。

通常,您會使用IoC容器(Autofac,StructureMap,Unity等)自動連接對象實例。因此,不要致電new AuditLog(),您可以致電IoC.Container.Resolve<IAuditLog>()

如果您想了解更多信息,請告知我們。

1

當你從方法如Factory方法創建AuditLog實例並且從IAuditLog接口派生出多於一個的AuditLogXXX類時,這實際上很有用。

因此,而不是使用此代碼:

IAuditLog objAuditLog = new AuditLog(); 

當你編寫一個接口,您會實際使用此代碼:

IAuditLog objAuditLog = LogFactory.GetAuditLog(); //This call is programmed to an interface 

其中GetAuditLog()是在LogFactory定義的接口類型的方法類如下:

class LogFactory 
{  
    public IAuditLog GetAuditLog() // This method is programmed to an interface 
    { 
     //Some logic to make a choice to return appropriate AuditLogXXX instance from the factory 
    }  
} 
+0

謝謝大家! – Wilky