里氏替换原则(Liskov's Substitution Principle)

里氏替换原则(Liskov’s Substitution Principle)

flyfish

解释

All the time we design a program module and we create some class
hierarchies.Then we extend some classes creating some derived
classes.We must make sure that the new derived classes just extend
without replacing the functionality of old classes.Otherwise the new
classes can produce undesired effects when they are used in existing
program modules. Likov’s Substitution Principle states that if a
program module is using a Base class, then the reference to the Base
class can be replaced with a Derived class without affecting the
functionality of the program module.

我们设计一个程序模块,我们创建一些类的层级结构,我们创建一些派生类以对类进行扩展
我们必须确保新的派生类只扩展而没有替换旧类的功能,否则当它们用于现有的程序模块时新的类会产生不想要的效果
里氏替换原则的情形是如果一个程序模块使用基类,对基类的引用可以用派生类替换而不会影响程序模块的功能。

//违反里氏替换原则的代码示例,更改正方形的一个边,更改了矩形的长宽
// Violation of Likov’s Substitution Principle

class Rectangle
 {
 protected:
     int m_width;
     int m_height;

 public:
     void setWidth(int width){
         m_width = width;
     }

      void setHeight(int height){
         m_height = height;
     }


     int getWidth(){
         return m_width;
     }

     int getHeight(){
         return m_height;
     }

      int getArea(){
         return m_width * m_height;
     }
 };

 class Square :public Rectangle
 {
 public:
         void setWidth(int width){
         m_width = width;
         m_height = width;
     }

      void setHeight(int height){
         m_width = height;
         m_height = height;
     }
 };
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

西笑生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值