设计模式03-SOLID(L)里式替换原则

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)}");
    
                    }
                }

     

posted @ 2022-05-11 10:58  后跳  阅读(24)  评论(0编辑  收藏  举报