Subtypes must be substitutable for their base types.子类必须可以替换基类编程
例:正方形IS-A矩形,所以咱们会设计成正方形继承至矩形,然而假若有如下代码:spa
public Rectangle IncreaseHeight(Rectangle r) { while(r.getHeight()<r.getWidth())) { r.setHeight(r.getHeight()++) } return r; }
就会有错误出现。设计
应用:在具体实如今,要求应该针对 “接口”或“抽象基类”进行编程,充分利用面向对象的多态特性,让实现同一接口或抽象基类的子对象能够互相取代而不影响到程序的其余部分。code
反例:.NET基类库中的ReadOnlyCollection类,ReadOnlyCollection<T>实现了ICollection<T>接口,但这接口中的Add()、Clear()方法对于只读集合是无心义的。对象
No client should be forced to depend on methods it does not use blog
不该该强迫一个软件组件依赖于它们不用的方法继承
例:IRepository接口既有“命令”(Save,Update)又有“查询”(Find,GetById)功能接口
public interface IRepository { public void Save(MyDataItem item); public void Update(MyDataItem item); public void Delete(int ItemId); public MyDataItem GetById(int ItemId); public List<MyDataItem> Find(Predicate<MyDataItem> pred); }
能够拆分为两个接口:ip
public interface IMutableRepository { public void Save(MyDataItem item); public void Update(MyDataItem item); public void Delete(int ItemId); } public interface IQueryableRepository { public MyDataItem GetById(int ItemId); public List<MyDataItem> Find(Predicate<MyDataItem> pred); }
依赖注入:类自己不直接实例化它所依赖的类的对象,而是由外界动态了将其“注入(inject)"ci