Advertisement
Caminhoneiro

Liskov Substitution Principle

Jul 11th, 2018
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.55 KB | None | 0 0
  1. // Liskov Substitution Principle
  2.  
  3. // Objects in a program should be replaceable with instances of their subtypes
  4. // w/o altering the correctness of the program
  5. #include "stdafx.h"
  6. #include <iostream>
  7.  
  8. class Rectangle
  9. {
  10. protected:
  11.   int width, height;
  12. public:
  13.  
  14.   Rectangle(const int width, const int height)
  15.     : width{width},
  16.       height{height}
  17.   {
  18.   }
  19.  
  20.  
  21.   virtual int GetWidth() const
  22.   {
  23.     return width;
  24.   }
  25.  
  26.   virtual void SetWidth(const int width)
  27.   {
  28.     this->width = width;
  29.   }
  30.  
  31.   virtual int GetHeight() const
  32.   {
  33.     return height;
  34.   }
  35.  
  36.   virtual void SetHeight(const int height)
  37.   {
  38.     this->height = height;
  39.   }
  40.  
  41.   int Area() const { return width*height; }
  42. };
  43.  
  44. class Square : public Rectangle
  45. {
  46. public:
  47.   Square(int size) : Rectangle{size,size} {}
  48.  
  49.   void SetWidth(const int width) override {
  50.     this->width = height = width;
  51.   }
  52.   void SetHeight(const int height) override {
  53.     this->height = width = height;
  54.   }
  55.  
  56. };
  57.  
  58. void process(Rectangle& r)
  59. {
  60.   int w = r.GetWidth();
  61.   r.SetHeight(10);
  62.  
  63.   std::cout << "expect area = " << (w * 10)
  64.     << ", got " << r.Area() << std::endl;
  65. }
  66.  
  67. // > 2. The solution of this project is actually build a factory with
  68. struct RectangleFactory
  69. {
  70.   static Rectangle CreateRectangle(int w, int h);
  71.   static Rectangle CreateSquare(int size);
  72. };
  73.  
  74. int main()
  75. {
  76.   Rectangle r{ 5,5 };
  77.   process(r);
  78.  
  79.     // > 1. If you override the rectangle with the square values it will give you the wrong result;
  80.   //Square s{ 5 };
  81.   //process(s);
  82.  
  83.   getchar();
  84.   return 0;
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement