Skip to content

Commit 827b206

Browse files
Shape drawing problem solved ✅
1 parent f6a2797 commit 827b206

File tree

1 file changed

+97
-0
lines changed
  • Learning_2.0/Solutions/Creational-pattern-solutions/shape-drawing-application

1 file changed

+97
-0
lines changed
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
// Shape.js - Prototype
2+
class Shape {
3+
constructor(color) {
4+
this.color = color;
5+
}
6+
7+
clone() {
8+
throw new Error("Method 'clone()' must be implemented.");
9+
}
10+
}
11+
12+
// Circle.js - Concrete Prototype
13+
class Circle extends Shape {
14+
constructor(radius, color) {
15+
super(color);
16+
this.radius = radius;
17+
}
18+
19+
clone() {
20+
return new Circle(this.radius, this.color);
21+
}
22+
23+
getDetails() {
24+
return `Circle: Radius = ${this.radius}, Color = ${this.color}`;
25+
}
26+
}
27+
28+
// Rectangle.js - Concrete Prototype
29+
class Rectangle extends Shape {
30+
constructor(width, height, color) {
31+
super(color);
32+
this.width = width;
33+
this.height = height;
34+
}
35+
36+
clone() {
37+
return new Rectangle(this.width, this.height, this.color);
38+
}
39+
40+
getDetails() {
41+
return `Rectangle: Width = ${this.width}, Height = ${this.height}, Color = ${this.color}`;
42+
}
43+
}
44+
45+
// Triangle.js - Concrete Prototype
46+
class Triangle extends Shape {
47+
constructor(base, height, color) {
48+
super(color);
49+
this.base = base;
50+
this.height = height;
51+
}
52+
53+
clone() {
54+
return new Triangle(this.base, this.height, this.color);
55+
}
56+
57+
getDetails() {
58+
return `Triangle: Base = ${this.base}, Height = ${this.height}, Color = ${this.color}`;
59+
}
60+
}
61+
62+
// ShapeManager.js - Client
63+
class ShapeManager {
64+
constructor() {
65+
this.shapes = {};
66+
}
67+
68+
addShape(key, shape) {
69+
this.shapes[key] = shape;
70+
}
71+
72+
cloneShape(key) {
73+
const shapeToClone = this.shapes[key];
74+
return shapeToClone ? shapeToClone.clone() : null;
75+
}
76+
}
77+
78+
// Example usage
79+
const shapeManager = new ShapeManager();
80+
81+
const circle = new Circle(10, "red");
82+
shapeManager.addShape("circle", circle);
83+
84+
const clonedCircle = shapeManager.cloneShape("circle");
85+
console.log(clonedCircle.getDetails()); // Circle: Radius = 10, Color = red
86+
87+
const rectangle = new Rectangle(5, 10, "blue");
88+
shapeManager.addShape("rectangle", rectangle);
89+
90+
const clonedRectangle = shapeManager.cloneShape("rectangle");
91+
console.log(clonedRectangle.getDetails()); // Rectangle: Width = 5, Height = 10, Color = blue
92+
93+
const triangle = new Triangle(6, 8, "green");
94+
shapeManager.addShape("triangle", triangle);
95+
96+
const clonedTriangle = shapeManager.cloneShape("triangle");
97+
console.log(clonedTriangle.getDetails()); // Triangle: Base = 6, Height = 8, Color = green

0 commit comments

Comments
 (0)