Singleton design pattern is preffered over globals, as they do not pollute the global scope and still makes sure that same class is not getting initiated every time you need it.
How does it work
Singleton methods/classes are self responsible for making sure that they are not re-initiating themselves.
Cache class can be a perfect example of singleton , becuase we want to share the cache store across our application and also making sure that we carry the same instance from one file to another.
Let's start by creating a
Cache class which as of now will only return and change the cache store name.
class Cache constructor: (@store='default') -> changeStore : (storeName) -> @store = storeName getStore : -> @store module.exports = Cache
What it is does is pretty simple , can be explained as follows:-
First we expect a store name while initiating a class , and set it's default value to
changeStoremethod will change the store name as expected.
getStorewill return the current store name.
So far our class is not singleton , as we have not written any code to make it singleton.
But let's see what problem will occur if we do not have singleton class for our Cache store.
## Requiring cache store Cache = require './Cache' ## Initiating and assigning store to variable cache cache = new Cache() ## Changing store name to users cache.changeStore 'users' ## Re intiating cache store and this time assigning it to another variable cache2 = new Cache() ## Getting current store name and output it to console console.log cache2.getStore()
If you will run the above file in browser or on server(using node) , you will find the final console prints
default. Where it should be
users as we changed the store name on line 8.
In brief , we are not able to maintain the state of our cache store which is important as it has to be shared across the application. At this point whether we can create a global variable and assign cache store to it or we should make our store singleton.
Making cache store singleton
class Cache ## Added new private variable called instance instance = null constructor: (@store='default') -> ## Added check to return same instance if !instance then instance = this return instance changeStore : (storeName) -> @store = storeName getStore : -> @store module.exports = Cache
We have added a private variable
instanceon line 4 , which will hold the your instance.
Finally we have added an
if statementto our constructor making sure we return the current instance or set it when does not exists.
Without changing a line code inside your
index.coffee file , you will see your console message returns
users instead of