Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Liskov subsitution principle */
- /*
- derived(pochodne) objects must be subtitutable (zastępowalne) for their base
- in renderLargeRectangles() for square we passed setWidth(4) and next setHeight(5) overwrites width&height. This would work for rectangles but not for squares.
- So you cant really substitute square for rectangles
- /* Projektując hierarchię klas, należy zrobić to tak, aby każda klasa pochodna mogła wykorzystywać wszystkie metody klasy bazowej bez konieczności ich przesłaniania. */
- in GOOD soulution you can subtitute Square and Rectangle with Shape class
- */
- class Rectangle {
- constructor() {
- this.width = 0;
- this.height = 0;
- }
- setColor(color) {
- // ...
- }
- render(area) {
- // ...
- console.log(area)
- }
- setWidth(width) {
- this.width = width
- }
- setHeight(height) {
- this.height = height
- }
- getArea() {
- return this.width * this.height
- }
- }
- class Square extends Rectangle {
- setWidth(width) {
- this.width = width;
- this.height = width;
- }
- setHeight(height) {
- this.width = height;
- this.height = height
- }
- }
- function renderLargeRectangles(rectangle) {
- rectangles.forEach(rectangle => {
- rectangle.setWidth(4);
- rectangle.setHeight(5);
- const area = rectangle.getArea(); // BAD: returns 25 for Square, should be 20
- rectangle.render(area)
- })
- }
- const rectangles = [new Rectangle(), new Rectangle(), new Square()];
- renderLargeRectangles(rectangles)
- /* GOOD */
- class Shape {
- setColor(color) {
- //...
- }
- render(area) {
- //...
- }
- }
- class Rectangle extends Shape {
- constructor(width, height) {
- super();
- this.width = width;
- this.height = height;
- }
- getArea() {
- return this.width * this.height;
- }
- }
- class Square extends Shape {
- constructor(length) {
- super();
- this.length = length;
- }
- getArea() {
- return this.length * this.length;
- }
- }
- function renderLargeShapes(shapes) {
- shapes.forEach(shape => {
- const area = shape.getArea();
- shape.render(area);
- })
- }
- const shapes = [new Rectangle(4, 5), new Rectangle(4, 5), new Square(5)]
Add Comment
Please, Sign In to add comment