Using a singleton to manage instances
Sometimes, there are objects that are resource intensive. They may require time, memory, battery power, or network usage that are unavailable or inconvenient. It is often useful to manage the creation and sharing of instances.
In this recipe, we'll see how to use singletons to manage instances.
Getting ready
This recipe assumes you already have a workspace that allows you to create and run ES modules in your browser. If you don't, please see the first two chapters.
How to do it...
- Open your command-line application and navigate to your workspace.
- Create a new folder named
09-05-singleton-to-manage-instances
. - Copy or create an
index.html
that loads and runs amain
function frommain.js
.
- Create a
main.js
file that defines a newclass
namedRocket
. Add a constructor takes aname
constructor argument and assigns it to an instance property:
// main.js class Rocket { constructor (name) { this.name = name; } }
- Create a
RocketManager
object that has arockets...