DEV Community

Moustafa Mahmoud
Moustafa Mahmoud

Posted on

How to share a single global object across your app (Singleton design pattern)

Image description

One of the most important features in OOP is you can create a single class and instantiate instances of it as many as you want.

but what if you need to create only a single object to deal with or make sure your class will be instantiated once ?

At this point implementing a Singleton will be a good choice.
and the singleton can represent the following objects

  • Database Connection Object
  • Current Logged-in user Object
  • Provisioning an OTP Object

or any kind of objects that you need to make sure there is only one instance of it in your app

How to implement

let's say we wanna create a counter and that counter will be available throughout your app.

Since in js we can create objects directly without creating a class first,

1- Create a variable that holds the current value of the counter and assign it an initial value

let currentValue = 0

2- Create an object to change the value with it

Since in js we can create objects directly without creating a class first, a simple counter object well be enough to implement a singleton

let currentValue = 0
const counter = {

increment(){
return ++currentValue
}

decrement(){
return --currentValue
}

}

Enter fullscreen mode Exit fullscreen mode




3- Prevent modifying the counter object and export it


let currentValue = 0
const counter = {

increment(){
return ++currentValue
}

decrement(){
return --currentValue
}

}
Object.freeze( counter )
export { counter }

Enter fullscreen mode Exit fullscreen mode




notes

  • We use const with counter object (the Singleton) to prevent reassigning it by mistake, also we freeze it to prevent adding or removing attributes or changing the value of one of them.
  • Since objects are passed by reference, you'll get the same instance every time you import it in another file
  • You can create more methods based on your requirements in your app, like creating a getter method to get the counter value.

hope that article answered your question and see you next time,

Thanks

Top comments (0)