1. 程式人生 > 其它 >設計模式04-裡式替換(兒子應大於等於父親)

設計模式04-裡式替換(兒子應大於等於父親)

Liskov Substitution Principle    裡式替換原則

  • Liskov Substitution: 里氏替換。在任何基類類出現的地方,子類能直接替代基類,也就是說,基類有任何修改,都不會對子類功能產生影響。

  • 以下例子:正方形是矩形嗎?
  • class Rectange
                {
                    //public  int width { get; set; }
                   // public  int height { get; set; }
                    public virtual int width { get
    ; set; } public virtual int height { get; set; } public Rectange() { } public Rectange(int width, int height) { this.width = width; this.height = height; }
    public override string ToString() { return $"{nameof(width)}:{width} .{nameof(height)}:{height}"; } } class Square:Rectange { // public new int width { set { base.width = base.height = value; } }
    // public new int height { set { base.height = base.width = value; } } public override int width { set { base.width = base.height = value; } } public override int height { set { base.height = base.width = value; } } } internal class Program { static public int Area(Rectange r) => r.width * r.height; static void Main(string[] args) { Rectange rc = new Rectange(2,3); Console.WriteLine($"{rc} has a area {Area(rc)}"); Rectange square = new Square(); square.width = 4; Console.WriteLine($"{square} has a area {Area(square)}"); } }