Prototype Design Pattern — 3 Minute Series
Is creating a new instance too expensive? Try this!
Sep 17, 2022
_00 / Concept
When you feel creating a new instance is expensive, then you can use Prototype Design Pattern to solve this problem. Remember, you need to know whether you are doing deep or shallow copy.
_01 / Key Roles
Clone method.
class Monster {
...states
constructor() {
this.init()
}
init() {
...super expensive process
}
clone() {
// shallow
return Object.assign({}, this)
}
}
_02 / Trade-offs
🟢 If the constructor process is too expensive, you might need it.
🟢 You can customize the cloning process if you need.
🟢 Alternative option for inheritance.
🔴 Shallow copy is always an issue, especially when your class depends on other objects.