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

如果对每一个类型为SS的对象O1O_1, 都有类型为TT的对象O2O_2, 使得以T定义的所有程序P在所有的对象O1O_1都代换成O2O_2时, 程序 P 的行为没有发生变化, 那么类型SS是类型TT的子类型。

另一种说法是:

Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it.

所有引用基类的地方必须能透明地使用其子类的对象。

阅读更多