Design pattern generally solves few typical programming challenges and makes it more scalable, reusable and meaningful.
It provides a generalized solution for frequently encountered problems, which typically tends to increase the total number of lines of code a program has to write.
The following are few benefits of understanding and using Design Patterns:
- Modular code
- Reusable code
- Increased readability
- More meaningful code from semantic perspective
- Avoid time consuming problems implicitly
- Reduce repetition of code
- Highly scalable code
- Supports object-oriented approach
Lets take Javascript and discuss design patterns in javascript to understand it better.
According to dimensions of code, on which a design pattern impacts, it can be categorized as follows:
- Creational Design Pattern
- Behavioral Design Pattern
- Structural Design Pattern
Lets take one type of pattern and see how design pattern solves the problem.
Creational Design Pattern
Creational design pattern basically deals with the way of creating objects in a way suitable to our requirements.
Different Creational design patterns can be used in different ways of creating objects as per our requirement. The basic ways of creating objects may not be suitable to all situations.
Lets discuss a good example of creational design pattern called “Singleton Pattern”
Singleton Pattern
This pattern ensure that, there is not, more than one instance of the class, ever created in the memory.
Whenever, you have to use same class with some initialization again and again we can make it as a singleton.
The object of this class should not be having the values being manipulated and changed over the time, because it is going be used several times at different fragment of time, in your code.
The script below implements Singleton Pattern:
var Person = (function(){ // Self calling function // Private property for holding the only existing instance var personInstance; var createPerson = function(){ // Private property initializing default pull capacity. var canPullWeight = 3; // Private method for increasing the value of canPullWeight. var canPull = function( kg ){ canPullWeight = kg; }; // Private method for passing increased value. var increaseEnergy = function( newVal ){ canPull( newVal ); }; // Private method for returning value of return canPullWeight, // at any point of time, from the one and only existing instance. var pullCapacity = function(){ return canPullWeight; }; return { // returns increaseEnergy method which is a // closure with access to private properties. increaseEnergy: increaseEnergy, getPullCapacity: pullCapacity }; }; return { // Method for creating instance of Person. getInstance: function(){ // Condition checking existence of instance if(!personInstance){ personInstance = createPerson(); } // If instance already existing returning the same. return personInstance; } }; })( ); // Creating firstPerson instance. var firstPerson = Person.getInstance( ); // alerts default value 3. alert(firstPerson.getPullCapacity()); // Creating secondPerson instance (Same instance is used) var secondPerson = Person.getInstance(); // Same output. Alerts default value 3. alert(secondPerson.getPullCapacity()); // Calling increaseEnergy Method of firstPerson with newVal as 20. // Note: we are not going to call increaseEnergy method of secondPerson. firstPerson.increaseEnergy( 20 ); // alerts new value which is 20. alert(firstPerson.getPullCapacity()); // It also alerts new value which is 20, as same instance is used alert(secondPerson.getPullCapacity());
Keep the following in mind when you are reviewing the above code:
- There is one and only one instance existing at any point of time during execution of code.
- firstPerson and secondPerson are using same instance of Person returned.
- Manipulating the value of firstPerson is impacting secondPerson also and vice-versa.
- More than one instance of Person class cannot be created because of condition check.
Singleton pattern can be used in the following cases:
- To have some properties to be initialized with some default values in the script.
- To have a single instance for a frequently accessed static value through out the script.
- Singleton pattern is also used for NameSpacing in javascript.
- Initializing database connection input parameters.
- Keeping package dependency list statically.
- Having single point of access for a frequently changing value, at any instant of time.
Comments on this entry are closed.
When i executing the above script, i am getting blank alerts.
Looks like there is an error/typo in the 1st line of code
var Person = (function()
should be
var Person = function()
@Anand: Its not an error/typo. The function which you are pointing is a self invoking function.
@Renga: In the above script, there is method “pullCapacity”. Its is currently left blank. Its an typo here. This method should return the value of the property “canPullWeight”.
Please run the script and see the result which will clarify your doubts.
For your reference the correction is as follows:
var pullCapacity = function(){
return canPullWeight;
};
@Renga and Anand: You can the run the script using the link below and go through the comments in the code to clarify your doubts about how it is working.
http://jsfiddle.net/paZ4w/1/
@Renga, @Anand,
A small correction was made to the code. It was missing this line: return canPullWeight;
Please try the code again. It should work now.
Hi Anand, In 1st line of code, its not a typo/error. The function which you are pointing is a self invoking function. So the syntax goes like :
(function(){
// Logic goes here
})();
Its creating a closure there. Please refer the article “Javascript Closure” @thegeekstuff.com
Why would I use this over a simple var database = {….} with functions inside it? Except for single instance for frequently accessed static value. (But a single var database is also singular?)
My guess is this is easier to integrate/maintain and safer as a simple var database can be overridden?