[英]Dependency Injection with Multiple Interfaces
我只是學習接口隔離原理。 但是在學習之后我對示例中的場景感到困惑。
這個概念是將接口分成簡單的接口。 那很好,但我的問題是層次結構模型與否?
以我在書中研究的例子為例。
我有一個產品接口具有以下屬性
public interface IProduct
{
decimal Price { get; set; }
decimal WeightInKg { get; set; }
int Stock { get; set; }
int Certification { get; set; }
int RunningTime { get; set; }
}
我只是簡化了界面中的一個類implmentation
public class DVD : IProduct
{
public decimal Price { get; set; }
public decimal WeightInKg { get; set; }
public int Stock { get; set; }
public int Certification { get; set; }
public int RunningTime { get; set; }
}
問題是當應用於沒有相關屬性的其他類別時。 為TShirt創建類時,不需要Certification和RunningTime。 因此,根據接口隔離原則,接口如下所示分開
創建一個新界面,將與電影相關的屬性移動到這個屬性,如下所示
public interface IMovie
{
int Certification { get; set; }
int RunningTime { get; set; }
}
所以IProduct沒有這些屬性和實現如下
public class TShirt : IProduct
{
public decimal Price { get; set; }
public decimal WeightInKg { get; set; }
public int Stock { get; set; }
}
public class DVD : IProduct, IMovie
{
public decimal Price { get; set; }
public decimal WeightInKg { get; set; }
public int Stock { get; set; }
public int Certification { get; set; }
public int RunningTime { get; set; }
}
在概念上我對此感到滿意。 但是,如果這關於真正的方法實現這樣。 當我使用依賴注入時,我使用哪個接口作為DVD類的類型。
我很困惑或者我錯過了什么? 如果我應用繼承邏輯,我們可以使用較低級別的接口,因此基接口也繼承。 但如果我這樣使用怎么能實現?
如果你知道什么,這是一個電影總是要還是一個產品,你可以定義你的接口像這樣,在IMovie
延伸IProduct
:
public interface IProduct
{
decimal Price { get; set; }
decimal WeightInKg { get; set; }
int Stock { get; set; }
}
public interface IMovie : IProduct
{
int Certification { get; set; }
int RunningTime { get; set; }
}
然后你的DVD
類就實現了IMovie
接口:
public class DVD : IMovie
{
public decimal Price { get; set; }
public decimal WeightInKg { get; set; }
public int Stock { get; set; }
public int Certification { get; set; }
public int RunningTime { get; set; }
}
使用您的其他例子,或許你的TShirt
實現了IClothing
接口,這也是一種產品:
public class IClothing : IProduct
{
int Size { get; set; }
Color Color { get; set; }
}
public class TShirt : IClothing
{
public decimal Price { get; set; }
public decimal WeightInKg { get; set; }
public int Stock { get; set; }
public int Size { get; set; }
public Color Color { get; set; }
}
現在,當你注入你的依賴,你可以要求的實例IMovie
或IClothing
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.