zoukankan      html  css  js  c++  java
  • What is an example of the Liskov Substitution Principle?

    What is an example of the Liskov Substitution Principle?

    回答1

    A great example illustrating LSP (given by Uncle Bob in a podcast I heard recently) was how sometimes something that sounds right in natural language doesn't quite work in code.

    In mathematics, a Square is a Rectangle. Indeed it is a specialization of a rectangle. The "is a" makes you want to model this with inheritance. However if in code you made Square derive from Rectangle, then a Square should be usable anywhere you expect a Rectangle. This makes for some strange behavior.

    Imagine you had SetWidth and SetHeight methods on your Rectangle base class; this seems perfectly logical. However if your Rectangle reference pointed to a Square, then SetWidth and SetHeight doesn't make sense because setting one would change the other to match it. In this case Square fails the Liskov Substitution Test with Rectangle and the abstraction of having Square inherit from Rectangle is a bad one.

    enter image description here

    Y'all should check out the other priceless SOLID Principles Motivational Posters.

    回答2

    The Liskov Substitution Principle (LSP, ) is a concept in Object Oriented Programming that states:

    Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it.

    At its heart LSP is about interfaces and contracts as well as how to decide when to extend a class vs. use another strategy such as composition to achieve your goal.

  • 相关阅读:
    nginx 安装部署
    cordova 安装使用
    git 设置和取消代理
    SQL语句 合并列值 将一列的多个值合并成一行
    idea 注册码 地址:
    mac 安装redis
    redisTemplate 方法
    js 点击 隐藏弹出层
    windows 安装redis
    docker 安装redis
  • 原文地址:https://www.cnblogs.com/chucklu/p/13715065.html
Copyright © 2011-2022 走看看