2013-03-04 59 views
1

我不明白的依賴反轉並在GOF書中提出了著名的短語之間的差異,「程序接口,而不是實現」。 DIP的定義說明了這些原則:DI原理和「程序到接口,而不是實現」有什麼區別?

  1. 高級模塊不應該依賴低級模塊。兩者都應該依賴於抽象。
  2. 抽象不應該依賴於細節。細節應該取決於抽象。

看來,這兩個原則都做同樣的事情:將接口與實現分離。

回答

2

「程序接口,而不是實現」是OOP中一般意義上的(即使你的語言不支持接口的概念)的好建議。這個想法是發送消息的對象不應該關心接收者的具體情況(例如,哪個類是實例的,或者它是否屬於給定的層次結構),只要它可以回答一組消息(從而執行一組行爲)。如果您看一下GoF中的模式,主要的底線之一是,只要您針對接口進行編程,就可以將目標對象替換爲另一個,而無需更改客戶端中的任何內容。

關於Dependency Inversion Principle我看到它,就像前理念的具體應用。爲了獲得靈活性和可重用性,您將編程思想應用於接口而非分層架構中的具體類,目的是將較低層與較高層解耦。

HTH

0

假設你有一個Computerclass定義如下:

public class Computer 
{ 
    public string OwnerName{get; set;} 

    public int RAMCapacity{get; set;} //Hardware based property 

    public string OperatingSystem{get; set;} //Software based property 
} 

現在,編程Interface說,按照上面的代碼中的註釋,你應該建立一個ISoftwareComponentsIHardwareComponents接口,然後將這些屬性到各自的接口和實現Computer類,如下兩個接口:

public interface ISoftwareComponents 
{ 
    string OperatingSystem{get; set;} 
} 

public interface IHardwareComponents 
{ 
    int RAMCapacity{get; set;} 
} 


public class Computer : ISoftwareComponent, IHardwareComponents 
{ 
    public string OwnerName{get; set;} 

    public int RAMCapacity{get; set;} //IHardwareComponents property 

    public string OperatingSystem{get; set;} //ISoftwareComponents property 
} 

現在對於Computer類客戶端代碼可以使用這樣的代碼:

Computer comp = new Computer(); 

//software requirements can use the below code: 
string os = ((ISoftwareComponents)comp).OperatingSystem; // and, other variations by method calls 

//hardware requirements can use the below code 
int memory = ((IHardwareComponents)comp).RAMCapacity; //and, other variations 

您也可以通過計算機的其他類和如下方法只有軟件和硬件接口部分:

public void SetHardware(IHardwareComponents comp) 
{ 
    comp.RAMCapacity = 512; 
} 

探索更多關於上面的例子,你會知道更多。

相關問題