什么是接口隔离原理,以及如何在C#中实现?
不应强迫客户端依赖于不使用的接口。
接口隔离原则指出,不应强迫客户端实现不使用的接口。
根据一组方法,最好使用许多小接口来代替一个胖接口,每个小接口服务一个子模块
接口隔离之前
示例
public interface IProduct { int ID { get; set; } double Weight { get; set; } int Stock { get; set; } int Inseam { get; set; } int WaistSize { get; set; } } public class Jeans : IProduct { public int ID { get; set; } public double Weight { get; set; } public int Stock { get; set; } public int Inseam { get; set; } public int WaistSize { get; set; } } public class BaseballCap : IProduct { public int ID { get; set; } public double Weight { get; set; } public int Stock { get; set; } public int Inseam { get; set; } public int WaistSize { get; set; } public int HatSize { get; set; } }
接口隔离后
示例
public interface IProduct { int ID { get; set; } double Weight { get; set; } int Stock { get; set; } } public interface IPants { int Inseam { get; set; } int WaistSize { get; set; } } public interface IHat { int HatSize { get; set; } } public class Jeans : IProduct, IPants { public int ID { get; set; } public double Weight { get; set; } public int Stock { get; set; } public int Inseam { get; set; } public int WaistSize { get; set; } } public class BaseballCap : IProduct, IHat { public int ID { get; set; } public double Weight { get; set; } public int Stock { get; set; } public int HatSize { get; set; } }