子型別必須可以被替換成它的基底型別
subtypes(衍生型別): 類別
base Types(基底型別): 介面、抽象類別、基底類別
LSP的精神:
- 每個衍生類別轉型時都能正確轉為基底類別
- 必須正確實作繼承與多型
第一版:沒有繼承,單純計算矩形面積
using System;
public class Program
{
public static void Main()
{
Rectangle o = new Rectangle();
o.Width = 40;
o.Height = 50;
LSPBehavior.GetArea(o).Dump();
}
}
public class Rectangle
{
public int Height
{
get;
set;
}
public int Width
{
get;
set;
}
}
public class LSPBehavior
{
public static int GetArea(Rectangle s)
{
if (s.Width > 20)
{
s.Width = 20;
}
return s.Width * s.Height;
}
}
新增需求,增加 Square 類別 (套用 OCP 原則)
using System;
public class Program
{
public static void Main()
{
Square o = new Square();
o.Width = 40;
// o.Height = 50;
LSPBehavior.GetArea(o).Dump();
}
}
public class Rectangle
{
public virtual int Height
{
get;
set;
}
public virtual int Width
{
get;
set;
}
}
public class LSPBehavior
{
public static int GetArea(Rectangle s)
{
if (s.Width > 20)
{
s.Width = 20;
}
return s.Width * s.Height;
}
}
public class Square : Rectangle
{
private int _height;
private int _width;
public override int Height
{
get
{
return _height;
}
set
{
_height = _width = value;
}
}
public override int Width
{
get
{
return _width;
}
set
{
_width = value;
_height = value;
}
}
}