里氏代换原则由Barbara Liskov于1988年提出,它最开始的定义如下: If for each object o1 of type S there is an object o2 of type T such that for all programs P defined in terms of T,the behavior of P is unchanged when o1 is substituted for o2 then S is a subtype of T. 另外一种提法如下: FUNCTIONS THAT USE POINTERS OR REFERENCES TO BASE CLASSES MUST BE ABLE TO USE OBJECTS OF DERIVED CLASSES WITHOUT KNOWING IT.
中文更好的描述如下: 如果对每一个类型为T1的对象o1,都有类型为T2的对象o2,使得以T1定义的所有程序P在所有的对象o1都代换成o2时,程序P的行为没有发生变化,那么类型T2是类型T1的子类型。 换言之:一个软件实体如果使用的是一个基类的话,那么一定适用于其子类,而且它根本不能察觉出基类对象和子类对象的区别。反过来代换是不成立的。 When considering whether a particular design is appropriate or not,one must not simply view the solution in isolation. One must view it in terms of the reasonable assumptions that will be made by the users of that design. 参考: 《Java与模式》,阎宏编著 《The Liskov Substitution Principle Principle》,by Robert C. Martin