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

前端之家收集整理的这篇文章主要介绍了里氏替换原则(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;
     }
 };
原文链接:https://www.f2er.com/javaschema/282901.html

猜你在找的设计模式相关文章