• 设计模式03SOLID(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)}");
      
                      }
                  }
  • 相关阅读:
    BZOJ3064: Tyvj 1518 CPU监控
    BZOJ3160: 万径人踪灭
    BZOJ3527: [Zjoi2014]力
    BZOJ2194: 快速傅立叶之二
    FFT模板
    Splay树再学习
    POJ2406 Power Strings KMP算法
    POJ2752 Seek the Name,Seek the Fame KMP算法
    POJ3461 Oulipo KMP算法
    POJ2004 Mix and build Trie树? dp?
  • 原文地址:https://www.cnblogs.com/Zingu/p/16257063.html
Copyright © 2020-2023  润新知