3、里氏代换原则(Liskov Substitution Principle, LSP)
定义
里氏替换原则是Barbara Liskov[1]与1988年提出来的。原文是:
What is wanted here is something like the following substitution property: If for each object of type S there is an object of type T such that for all programs P defined in terms of T, the behavior of P is unchanged when is substituted for then S is a subtype of T
如果对每一个类型为
的对象 , 都有类型为 的对象 , 使得以T定义的所有程序P在所有的对象 都代换成 时, 程序 P 的行为没有发生变化, 那么类型 是类型 的子类型。
另一种说法是:
Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it.
所有引用基类的地方必须能透明地使用其子类的对象。