[英]Program to an interface not an implementation confusion
我正在嘗試養成對接口而不是對實現進行編碼的習慣,盡管在大多數情況下,我可以看到推理的原因,但仍有一些困難。
舉一個非常簡單的例子:
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");
}
}
實例化時我仍然必須使用AuditLog,所以有什么意義呢? 如果AddLog方法簽名發生變化,我仍然必須遍歷所有使用它的頁面並修改代碼。 我錯過了重點嗎?
謝謝您的任何提前幫助,威爾基。
在示例中,如果您使用DatabaseAuditLogger()
或EventLogAuditLogger()
切換了FileAuditLogger()
,則可以切換實現而不必重寫代碼。
通常,您會使用IoC容器(Autofac,StructureMap,Unity等)來自動連接對象實例化。 因此, IoC.Container.Resolve<IAuditLog>()
調用new AuditLog()
, IoC.Container.Resolve<IAuditLog>()
調用IoC.Container.Resolve<IAuditLog>()
讓我知道您是否需要更多信息。
假設有兩個AuditLog類
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");
}
現在,您可以在運行時基於某些配置注入任何類,而無需更改實際實現
這並不一定意味着您必須實際使用C# interface
。 OOP術語中的接口是API的公開可見外觀。 這是一項合同,應指定外部可見的操作結果。 它在表面下的確切工作方式無關緊要,這樣您就可以隨時交換實現。
當然,就此而言, interface
是一種能夠使用不同實現的方法,但是抽象基類甚至是其他人可以從中獲得的非抽象類也是如此。
但是,更確切地說,是您的問題:當然,在實例化一個類時,必須知道其類型,但是不必一定要在該實例中創建類實例。 您可以從外部設置IAuditLog
,也可以通過工廠類等獲取它,在代碼的那個確切點上,您將不知道該類是什么類型(除了與IAuditLog
兼容)。
當您從諸如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
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.