Understand Design Patterns in JavaScript

Today, we’re going to discuss common design pattern used in JavaScript. Design patterns are ways of programming which offers developers to do code more maintainable, reusable and scalable. Patterns are necessary when developing large application in JavaScript. If you’re in becoming a better Javascipt developer, then it’s for you.

So solid design patterns are the basic building block for maintainable software applications. In this tutorial, we’ll take a look at a few patterns that you can start using today. First we will know what’s design patterns and then go in details.

What is a Design Pattern?

A pattern is a reusable solution that can be applied to commonly occurring problems in software design and development. As over the many years of practicing software development, experts have figured out ways of solving similar problems. These solutions have been encapsulated into design patterns. So, why is it important to understand patterns and be familiar with them? Design patterns have three main benefits:

  • Patterns are proven solutions:They provide solid approaches to solving problems in software development using proven techniques that reflect the experience and insights the developers that helped define them bring to the pattern.
  • Patterns can be easily reused:A pattern offers reusability to similar tasks.
  • Patterns can be expressive:They provides a set of clear structure and vocabulary to the solution that can help express rather large solutions quite elegantly

A Design patterns can also be broken down into a number of different categories. Now we’ll review three of these categories and briefly mention a few examples of the patterns that fall into these categories before exploring specific ones in more detail.

Categories Of Design Pattern

In software development, design patterns are generally grouped into a few categories. We’ll cover the three most important ones in this tutorial. They are explained in brief below:

  • Creational Design Patterns
  • Structural Design Patterns
  • Behavioral Design Patterns

Creational Design Patterns

The creational design patterns mainly focus on handling object creation mechanisms where objects are created in a manner suitable for the situation we’re are working in. These patterns aim to solve problem by controlling the creation process. Some of the patterns that fall under this category are: Constructor, Factory, Abstract, Prototype, Singleton and Builder. Here in this tutoria, we cover Builder pattern.

Builder Pattern

The Builder Pattern is often used in web development, and you’ve probably used it before without realizing it. When working with the DOM, we often want to construct new elements dynamically – a process which can increase in complexity depending on the final markup, attributes and properties we wish our constructed elements to contain.

Builders Pattern allow us to construct complex objects by only specifying the type and content of the object, shielding us from the process of creating or representing the object explicitly.

For example, you’ve probably done this countless times in jQuery. The jQuery dollar sign allows us to do just this as it provides a number of different means for dynamically building new jQuery objects, by either passing in the complete markup for an element, partial markup and content or using the jQuery for construction:

  1. $( ‘<div class=”foo”>bar</div>’ );  
  2.   
  3. $( ‘<p id=”test”>foo <em>bar</em></p>’).appendTo(“body”);  
  4.   
  5. var newParagraph = $( “<p />” ).text( “Hello world” );  
  6.   
  7. $( “<input />” )  
  8.       .attr({ “type”“text”“id”:“sample”});  
  9.       .appendTo(“#container”);  

Structural Design Patterns

Structural design patterns are really useful when figuring out how a system should work. The patterns that fall under this category include: Decorator, Facade, Flyweight, Adapter and Proxy. Here We’re going to look at the Facade pattern.

Facade pattern

Facades are a structural pattern which can often be seen in JavaScript libraries like jQuery where, although an implementation may support methods with a wide range of behaviors, only a “facade” or limited abstraction of these methods is presented to the public for use.

The Facade pattern provides the user with a convenient higher-level interface to a larger body of code, hiding its true underlying complexity.

The Facade pattern always improves usability of a piece of software. Using jQuery as an example, one of the more popular methods of the library is the ready() method:

  1. $(document).ready(function() {  
  2.     // your code goes here…  
  3. });  

In a similar manner, we’re all familiar with jQuery’s $(document).ready(..). Internally, this is actually being powered by a method called bindReady(), which is doing this:

  1. bindReady: function() {  
  2.     …  
  3.     if ( document.addEventListener ) {  
  4.       // Use the handy event callback  
  5.       document.addEventListener( “DOMContentLoaded”, DOMContentLoaded, false );  
  6.   
  7.       // A fallback to window.onload, that will always work  
  8.       window.addEventListener( “load”, jQuery.ready, false );  
  9.   
  10.     // If IE event model is used  
  11.     } else if ( document.attachEvent ) {  
  12.   
  13.       document.attachEvent( “onreadystatechange”, DOMContentLoaded );  
  14.   
  15.       // A fallback to window.onload, that will always work  
  16.       window.attachEvent( “onload”, jQuery.ready );  
  17.                …  

As we know the ready() method is not all that simple. jQuery normalizes the browser inconsistencies to ensure that ready() is get fired at the appropriate time. However, as a developer, you are presented with a simple interface.

Behavioral Design Patterns

Behavioral patterns focus on improving or streamlining the communication between disparate objects in a system. The behavioral patterns has patterns such as Iterator, Mediator, Observer and Visitor. In this section, we’re going to look at the Observer patterns.

Observer patterns

The Observer is a design pattern where an an object maintains a list of objects depending on observers which automatically notifying them of any changes to state.

When something changes in our subject that the observer may be interested in, a notify message is sent which calls the update method in each observer. When the observer is no longer interested in the subject’s state, they can simply detach themselves

We can now expand on what we’ve learned to implement the Observer pattern with the following components:

  • Subject: maintains a list of observers, facilitates adding or removing observers
  • Observer: provides a update interface for objects that need to be notified of a Subject’s changes of state
  • ConcreteSubject: broadcasts notifications to observers on changes of state, stores the state of ConcreteObservers
  • ConcreteObserver: stores a reference to the ConcreteSubject, implements an update interface for the Observer to ensure state is consistent with the Subject’s

Now we’ll see a model with the Subject and the ability to add, remove or notify observers on the observer list.

  1. function Subject(){  
  2.   this.observers = new ObserverList();  
  3. }  
  4.   
  5. Subject.prototype.AddObserver = function( observer ){  
  6.   this.observers.Add( observer );  
  7. };    
  8.   
  9. Subject.prototype.RemoveObserver = function( observer ){  
  10.   this.observers.RemoveAt( this.observers.IndexOf( observer, 0 ) );  
  11. };    
  12.   
  13. Subject.prototype.Notify = function( context ){  
  14.   var observerCount = this.observers.Count();  
  15.   for(var i=0; i < observerCount; i++){  
  16.     this.observers.Get(i).Update( context );  
  17.   }  
  18. };  

The Observer pattern is one of the simpler patterns to implement, but it is very powerful. JavaScript is well suited to adopt this pattern as it’s naturally event-based.

As the major point about the design patterns is that most of us already applied these patterns successfully in the past without knowing about it. There are plenty of open-source code that implement various patterns in JavaScript. As web developer, we need to be aware of what patterns are out there and when to apply them. Hope, you will come up with these new ideas and concept about patterns.

Related posts:


About the Author

A web developer who has a love for creativity and enjoys experimenting with various techniques in both web design and development. If you would like to be kept up to date with our posts, you can follow us on Twitter, Facebook, Google+, or even by subscribing to our RSS Feed.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>