In out healthcare application, initially we decided to open a separate tab whenever a user click on a new window. While this was appreciated – as it allowed user to book multiple appointments / registration / admission simultaneously, we had a challenge in ensuring that the manage entity interfaces are being refreshed appropriately. One of the answer was to ensure that – we should launch only one instance of entity listing windows. This is where Javascript singleton implementation is very handy.
Singleton design pattern
Singleton pattern is a design pattern which restricts instantiation of a class to only one object. This is useful when exactly one object is needed across the system. The Singleton pattern provides a single point of access to a particular instance. Implementation of a singleton pattern must satisfy the single instance and global access principles.
How implementation of Singleton is being done in HaMSa
Implementation of Singleton design pattern for search window in HaMSa has been done by using the following steps:
- Created one function(Class) named InstanceFactory.js which is responsible to provide instance of class for which someone requests. If instance is already exist then it will return the same instance.
- For this I have taken a local config object (instance) and two methods named getInstance( nodeId ) and removeInstance( winId ).
- Initially config object will be empty and it is not visible from the outside.
- getInstance method is taking nodeId as a parameter because I am going to use this method to instantiate all the search window.
- removeInstance is responsible to set null the particular property of config object that instance has been destroyed.
- Based on this nodeId it will instantiate object , create property in config object , assign instantiated object to the config property and return the particular property of the config.
Following code shows how the Singleton for all the search windows is implemented in HaMSa:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
InstanceFactory = function(){ var instance = {}; return { removeInstance : function( winId ){ instance['Win'+ winId] = null; }, getInstance : function( nodeId ){ if( nodeId === windowCode.referralList ){ if( Ext.isEmpty( instance['Win'+nodeId] )){ instance['Win'+nodeId] = new administration.referralManagement.ReferralsList(); // an example window - you need to handle this in a generic way return instance['Win'+nodeId]; } else{ return instance['Win'+nodeId]; } } }(); |
Visit Walking Tree’s blog and forum for more help related to ExtJS, Javascript and Web development.