编程中的设计原则与函数式编程基础
1. 里氏替换原则(Liskov Substitution Principle,LSP)
里氏替换原则指出,如果一个接口接受一个父类型的对象,那么它也应该能够接受一个子类型的对象,而不会出现任何问题。更正式的定义是:设 𝜙(𝑥) 是关于类型 T 的对象 𝑥 可证明的属性,那么对于类型 S(S 是 T 的子类型)的对象 𝑦,𝜙(𝑦) 也应该为真。
1.1 违反 LSP 的示例
我们来看一个违反 LSP 的例子。首先定义一个矩形类:
public class Rectangle
{
public int Width { get; set; }
public int Height { get; set; }
public Rectangle() {}
public Rectangle(int width, int height)
{
Width = width;
Height = height;
}
public int Area => Width * Height;
}
然后定义一个正方形类,它继承自矩形类:
public class Square : Rectangle
{
public Square(int side)
{
Width = Height = side;
}
public new
超级会员免费看
订阅专栏 解锁全文
5095

被折叠的 条评论
为什么被折叠?



