Inheritance vs Composition
Inheritance
- 'is a' relationship
- "A Window is a Rectangle"
class Rectangle {
height: number;
width: number;
area(): number;
}
class Circle {
radius: number;
area(): number;
}
class Wall extends Rectangle {
color: string;
}
class RectangleWindow extends Rectangle {
open: boolean;
toggleOpen(): void;
}
class CircleWindow extends Circle {
open: boolean;
toggleOpen(): void;
}
Composition
- 'has a' relationship
- "A Window has a Rectangle"
- Composition is not adequate when there is bidirectional relationship between the classes
class Wall {
constructor(public shape: Shape) {}
color: string;
area(): number {
shape.area();
} // A Reference to the area of the shape Shape!
dimensions: Shape; // The dimensions references a Shape! (Rectangle or Circle)
}
class Window {
constructor(public shape: Shape) {}
open: boolean;
toggleOpen(): void;
area(): number {
shape.area();
} // A Reference to the area of the shape Shape!
dimensions: Shape; // The dimensions references a Shape! (Rectangle or Circle)
}
// The interface forces the Shape object to have a area method
interface Shape {
area(): number;
}
class Rectangle {
height: number;
width: number;
area(): number;
}
class Circle {
radius: number;
area(): number;
}