Singleton Pattern
Used when only a single instance of an object should exists and that instance
should be the one used no matter who or what is calling or using
the state or abilities of that object type. Used mostly when a system requires
an orchestrating object to hold state or have abilities that must be shared
across the entire system.
Benefits
– Delayed instantiation: the singleton object is not created until the first calling
to the object is received and a reference to that object is then held for the life
of the system’s execution.
– Exists across the entire system: the singleton when subsequently called
for use, will provide the caller a reference to the exact object instance that was
created upon first call.
– Consistent interface for accessing the singleton object: there is a function or object
that handles the creation of and holds the reference to the single object instance.
let dataContextSingleton = (function(){ // Holds the reference to the singleton object instance var singletonInstance; // Private function used to build the singleton object instance if it // does not yet exist function init(){ // Private state/functions for singleton object let _objectCollection = []; // Public state/functions function add(obj){ _objectCollection.push(obj); } function find(id){ let found = []; for(let obj of _objectCollection){ if(obj.id === id) found.push(obj); } return found; } // Using module reveal pattern to expose API return { add, find }; } // Returns the singleton management object used to get a reference to the // the singleton object instance return { getInstance: function(){ // if singleton instance does not exist, create it if(!singletonInstance){ singletonInstance = init(); } return singletonInstance; } } })(); let firstContext = dataContextSingleton.getInstance(); firstContext.add({ id: 1, name: 'test' }); let secondContext = dataContextSingleton.getInstance(); let found = secondContext.find(1); // When printed to the console, will see that the found array contains // the object with id 1 that was added by the first reference to the // dataContextSingleton. console.log(found);
Published by