我只是学习界面分离原则。但是在学习之后我对示例中的场景感到困惑。
概念是将接口分成简单的接口。那很好,但我的问题是关于层次结构模型吗?
以我在书中学习的例子为例。
我有一个具有以下属性的产品界面
public interface IProduct
{
decimal Price { get; set; }
decimal WeightInKg { get; set; }
int Stock { get; set; }
int Certification { get; set; }
int RunningTime { get; set; }
}
我只是从界面
中简化了一个类的实现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类的类型。
我很困惑或者我错过了什么?如果我应用继承逻辑,我们可以使用较低级别的接口,因此基接口也继承。但如果我这样用,怎么可以实现呢?
答案 0 :(得分:7)
如果您知道某部电影总是也是一种产品,您可以定义这样的界面,其中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
的实例。