What makes JavaScript different from other programming languages is the variety of design patterns offered by it-which make the code more organized, maintainable and offers more control. Well,so much pampering for the users :D.But,the design pattern to be used depends largely on the problem that you are trying to solve and the underlying pros and cons of using one pattern over the other.Whatever be the case,there are various number of patterns to choose from and it’s highly likely that you would find a pattern matching your requirements. Let’s go through some of the design patterns.

MODULE PATTERN

Modules are an inevitable part of any application that makes various parts of the code separated and organised at the same time.This pattern encapsulates privacy and organisation.It is undoubtedly the most widely used design pattern and has been seen in many projects like jQuery.It was originally designed to provide public and private encapsulation in classes. The main focus lies in reducing the usage of global variables thereby decreasing the chances of collision with other code in the application.

Before we start discussing the module pattern in JavaScript,let’s recall the access specifier that we’ve been using in our code for so long:

public : members that can be accessed from anywhere

private : members that can be accessed from inside the object

privileged : members that can only be directly accessed from inside the object, but which can be indirectly accessed from outside via a public method.

You won’t find the terms “private”,”public” or “protected” appearing in your code though-but privacy can still be obtained.This is where the use of closures  i.e. function scoping comes to the rescue.Variables or methods that are declared are only available to the module itself.However,those defined in the return statement are available to everyone.Consider the following code extract:

var Person=(function()

{

	var Salary;                       		//private property

	function increment(amt){                   	//private method

		if(amt<0){

			console.log("Oops!Enter correct amount");

		}else{
			salary=amt+10000;
		}
	};

	return {

		occupation: "service";              //public property

		change Occ: function(occ){          //public method
				this.occupation=occ;
		},
		total: function(income){            //privilege method
			increment(income);
		}
	};
})();

Now consider:

var teacher=Person(-5000);

You’ll get a message saying “Oops!Enter correct amount”.However,something like console.log(Person.salary); is undefined as “salary” isn’t exposed as a part of the public interface.

ADVANTAGES

  • Because functions are named and defined in the usual manner,showing stack calls becomes easy which further aids in the debugging
  • It promotes self-contained code and thus less clustering reduces the chances of collision with other JavaScript code.

DISADVANTAGES

  • Even if you add some additional functionality to the object containing the module,you won’t be able to access them as they will be available to the function declared within the closure.Thus it leaves limited scope for expansion.

Having stated so much,this module won’t let you down in situations where you need privacy for some of your data and a public interface.

SINGLETON PATTERN

This pattern is thus known because it limits the instantiation of a class to a single object.This object is called singleton.It is useful in situations where actions from across the system need to be coordinated from a central place or in other words,when various parts of an application try to access the shared resource. It’s working would be clear from the following example:

var Singletonclass = (function()

{

    var myinstance; //stores reference to the singleton

    function display() //singleton

    {

        function privatemethod() { //private method

            console.log("Hello!I'm private.");

        }

        var name1 = "Private name"; //private property

        return

        {

            publicmethod: function() { //public method

                console.log("Hi there! I'm public.");

            },

            var name2 = "Public name",

                getname: function() {

                    return name1;
                }

        };

    };

    return {

        if (!myinstance) {

            myinstance = display();

        }

        return myinstance;

    }

};

})();

Now if you try something like:

var instance1=Singletonclass.getname();

var instance2=Singletonclass.getname();

then both instance1 and instance2 refer to the same myinstance. Here the term “Lazy Load” comes into the picture.It’s a memory saving technique that creates instances when absolutely necessary.The getname() function illustrates this.If an instance to a singleton doesn’t exist,it is created-else not!This assures that there is a single instantiation of the class.

ADVANTAGES

  • Singleton classes must be memory-leak free. The instance of the singleton class is to be created once and it remains for the lifetime of the application.
  • A real singleton class is not easily extensible.
  • Derive the singleton class from an interface. This helps while doing unit testing .

DISADVANTAGES

  • The primary feature of the pattern is the disadvantage as well-i.e. creation of a single instance for a class.In most situations you need more than one instance for a class.
  • Singletons promote tight coupling between the classes hence making debugging cumbersome.

PROTOTYPE PATTERN

This pattern is based on JavaScript’s prototypal inheritance where we create objects that act as prototypes for other objects.The objects created are simple clones of the original object.It’s pretty simple to implement and takes advantage of the prototypal strengths of JavaScript.

function Car() {

    name: "Ferrari"

        wheels: 4

        color: "Red"

}

var myCar = Object.create(Car);

 

Then something like console.log(myCar.name) would print “Ferrari”.This shows that one is prototype of the other.This pattern is useful in situations when the subclasses don’t differ much-so copies of objects are created,modifying them as necessary.

ADVANTAGES

  • Instead of creating a brand new object,copies of objects are created and modified as per the need.Thus reducing the need for creating new objects
  • Object once created and initialized can be used again and again to create copies of itself, i.e. it promotes reusability.Instead of creating a whole new object,the code could be optimised as per the object’s use.

DISADVANTAGES

  • Classes that have circular references to other classes cannot be cloned.
  • Object has to be declared through use of “new” keyword – no auto-invoking.
  • Difficult to fix bugs with public methods if they are referred to as different methods privately.

 

Indeed, the design patterns offered by JavaScript are fascinating and interesting. By providing common reusable solutions to the problems,they help in optimizing the code.Being reusable and expressive,patterns provide a way to structure the program.The don’t provide exact solutions-just a solution scheme.Which pattern to use in a situation is your call.What is required is a careful analysis-and you are good to go!

 

 

1 thought on “Design Patterns in JavaScript”

  1. I discovered your blog site on google and check a couple of of your early posts. Continue to keep up the excellent operate. I just further up your RSS feed to my MSN News Reader. Looking for forward to reading extra from you later on!…

Leave a Reply

%d bloggers like this: