Design: Open/Closed Principle Application Design
Focus on designing a module or component demonstrating the Open/Closed Principle. Out of scope are specific UI or database implementations.
Functional Requirements
Non-Functional Requirements
+---------------------+
| Client Code |
+----------+----------+
|
v
+----------+----------+
| Abstract Feature |<-- Interface or Abstract Class
+----------+----------+
|
+--------+--------+--------+
| | | |
+---v---+ +--v---+ +--v---+ +--v---+
|Feature| |Feature| |Feature| |Feature|
| Impl1 | | Impl2 | | Impl3 | | Impl4 |
+-------+ +-------+ +-------+ +-------+
Client interacts with Abstract Feature interface.
New features add new implementations without changing existing code.class Shape {
area() { return 0; }
}
class Rectangle extends Shape {
constructor(width, height) {
super();
this.width = width;
this.height = height;
}
area() { return this.width * this.height; }
}
class Circle extends Shape {
constructor(radius) {
super();
this.radius = radius;
}
area() { return Math.PI * this.radius * this.radius; }
}
function totalArea(shapes) {
return shapes.reduce((sum, shape) => sum + shape.area(), 0);
}class Report {
generate(type) {
if (type === 'pdf') {
// generate PDF
} else if (type === 'html') {
// generate HTML
}
}
}Pass the test and this pattern moves unknown