-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFlyweight.js
More file actions
46 lines (36 loc) · 1.15 KB
/
Copy pathFlyweight.js
File metadata and controls
46 lines (36 loc) · 1.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// Optimize memory usage by sharing robot type instances (e.g., model, weapon) across multiple robot objects.
class RobotType {
constructor(type, weapon, model) {
this.type = type;
this.weapon = weapon;
this.model = model;
}
render(x, y) {
console.log(`[${this.type}] Model: ${this.model} | Weapon: ${this.weapon} at (${x}, ${y})`);
}
}
class RobotFactory {
static robotTypes = new Map();
static getRobotType(type, weapon, model) {
const key = `${type}_${weapon}_${model}`;
if (!this.robotTypes.has(key)) {
this.robotTypes.set(key, new RobotType(type, weapon, model));
}
return this.robotTypes.get(key);
}
}
class Robot {
constructor(x, y, robotType) {
this.x = x;
this.y = y;
this.robotType = robotType;
}
render() {
this.robotType.render(this.x, this.y);
}
}
const robots = [];
robots.push(new Robot(1, 2, RobotFactory.getRobotType("FlyRobot", "Laser", "AeroX")));
robots.push(new Robot(3, 4, RobotFactory.getRobotType("FlyRobot", "Laser", "AeroX")));
robots.push(new Robot(5, 6, RobotFactory.getRobotType("LandRobot", "Missile", "TankRex")));
robots.forEach(robot => robot.render());