GitHub LinkedIn RSS
Showing posts with label Design Patterns. Show all posts
Showing posts with label Design Patterns. Show all posts
Saturday, November 8, 2014

JavaScript Adapter Design Pattern


Today we'll continue the JavaScript Design Patterns series by discussing the Adapter Pattern. Adapters are added to existing code to reconcile two different interfaces. They allows programming components to work together that otherwise wouldn't because of mismatched interfaces.

Adapter may be also used to ease the use with the existing interface. If the existing code already has an interface that is doing a good job, there may be no need for an adapter. But if an interface is unintuitive or impractical for the task at hand, you can use an adapter to provide a cleaner or more option-rich interface. Let's see how it looks in the following illustration:


Here we depict the example of legacy IDataManager interface, which is deeply used within the system. With the introduction of Redis database into the system, we need an adapter to fill the gaps. Our Adapter class has to implement the getData method, to make it consistent with the system, calling in turn the scan method to iterate over data stored in the database.

The implementation will look something like this:
function RedisDataManager() {
    this.connect = function() {
        console.log('Connect to database');
    };

    this.scan = function() {
        return 'Data from database';
    };
}

function DataManager() {
    this.getData = function() {
        return 'Legacy data';
    }
}
  
function Adapter() {
    var redis = new RedisDataManager();
    redis.connect();
    
    this.getData = function() {
        return redis.scan();
    }
}

function Client(dataManager) {
    console.log(dataManager.getData());
}

var client = new Client(new Adapter());
As you can see our Client is oblivious about the IDataManager implementation, and using the Adapter Pattern, we connect the RedisDataManager to it.

Next time we'll continue our discussion about structural patterns by introducing Bridge Pattern, which is very much alike.
Wednesday, September 17, 2014

JavaScript Singleton Design Pattern


In the previous articles we discussed Factory, Builder and Prototype design pattern. Today it's time to draw a line under creational design patterns by talking about Singleton Pattern.

Even though it's the most well known design pattern among the developers, the thought of writing one in JavaScript, makes most developers tremble. Naturally there is no reason for that and in fact implementing it is not that big of a deal. But first, let's see how it looks in the following illustration:


Basically our singleton contains one instance of itself and returns only it. Client cannot create a new instance or get other instance then one proposed by singleton.

So how do we implement it? The same way, like in any other language - using static classes. To brush off the rust, please read Object Oriented JavaScript article.
var Singleton = (function () {
    var instance;
 
    function createInstance() {
        var object = new Object();
        return object;
    }
 
    return {
        getInstance: function () {
            if (!instance) {
                instance = createInstance();
            }
            return instance;
        }
    };
})();

var instance1 = Singleton.getInstance();
var instance2 = Singleton.getInstance();

console.log("Same instance? " + (instance1 === instance2));  
var instance3 = new Singleton();
In our example we get two instances and check if they are the same. They are! Later we try to create our own instance using new keyword, which of course fails.
Same instance? true
TypeError: object is not a function
Next time we'll talk about behavioral design patterns. Come prepared ;-)
Sunday, August 17, 2014

JavaScript Prototype Design Pattern


Let's continue our discussion about JavaScript Design Patterns. We've already talked about Factory and Builder pattern. Today I'll overview the Prototype pattern.

The Prototype pattern creates new objects by cloning one of a few stored prototypes. The Prototype pattern has two advantages: it speeds up the instantiation of very large, dynamically loaded classes (when copying objects is faster), and it keeps a record of identifiable parts of a large data structure that can be copied without knowing the subclass from which they were created. Have a look at the following illustration, depicting the pattern:


While there is a lot of information about cloning on the internet and even some suggest using it in the prototype design, the external approach is utterly incorrect. However since we are Object Oriented programmers, we would like to clone both public and private members. None of the external approaches will give you such result. On the other hand, if you will be willing to settle with public members cloning, might as well use parse/stringify methods combination of JSON class, which give the best results according to the cloning performance tests.

Implementation


We'll be basing our classes on JsDeepDive.Common.Manager example from Object Oriented JavaScript article, to show the effect on both public and private members:
var JsDeepDive = JsDeepDive || {};

function deepClone1(obj) {
  return JSON.parse(JSON.stringify(obj));
}

(function (key) {
 "use strict";
 JsDeepDive.PrototypedEntity = function (someParameter) {
  /* Start private parameters and functions of the class */
  var privates = {
   privateMember: undefined, 

   getPrivateMember: function getPrivateMember() {
    return this.privateMember;
   },   

   setPrivateMember: function setPrivateMember(value) {
    this.privateMember = value;
   },

   _constructor: function _constructor(someParameter) {
    this.privateMember = someParameter;
   }
  };
  /* End private parameters and functions of the class */

  this._ = function (aKey) {
   return key === aKey && privates;
  };
  privates._constructor(someParameter);        
 };

 JsDeepDive.PrototypedEntity.prototype = {
  getPrivateMember: function getPrivateMember() {
   return this._(key).getPrivateMember();
  },

  setPrivateMember: function setPrivateMember(test) {
   return this._(key).setPrivateMember(test);
  },
  publicMember: 1
 };
}({}));

var a = new JsDeepDive.PrototypedEntity(3);
a.setPrivateMember(2);
a.publicMember = 5;
console.log('a.privateMember: ' + a.getPrivateMember());
console.log('a.publicMember: ' + a.publicMember);
var b = deepClone1(a);
console.log('b.publicMember: ' + b.publicMember);
console.log('b.privateMember: ' + b.getPrivateMember());
Once you run the example, you'll encounter into error on line 53, since _ method is undefined, when called in line 36. Let's change things a bit. First we'll extend our _ method, so that we could update the privates property.
this._ = function (aKey, newPrivates) {   
 if (key !== aKey) {
  return;
 }
 if (newPrivates) {
  privates = newPrivates;
 } else {
  return privates;
 }
};
Next thing we do is to add a clone method, which will clone all public and privates using our new _ method:
clone: function clone() {
 var obj = {};
 for(var key in this) {
        obj[key] = this[key];
    }
 obj._(key, this._(key));
 return obj;
}
Now the full pattern:
var JsDeepDive = JsDeepDive || {};

function deepClone1(obj) {
  return JSON.parse(JSON.stringify(obj));
}

(function (key) {
 "use strict";
 JsDeepDive.PrototypedEntity = function (someParameter) {
  /* Start private parameters and functions of the class */
  var privates = {
   privateMember: undefined, 

   getPrivateMember: function getPrivateMember() {
    return this.privateMember;
   },   

   setPrivateMember: function setPrivateMember(value) {
    this.privateMember = value;
   },

   _constructor: function _constructor(someParameter) {
    this.privateMember = someParameter;
   }
  };
  /* End private parameters and functions of the class */

  this._ = function (aKey, newPrivates) {   
   if (key !== aKey) {
    return;
   }
   if (newPrivates) {
    privates = deepClone1(newPrivates);
   } else {
    return privates;
   }
  };
  privates._constructor(someParameter);        
 };

 JsDeepDive.PrototypedEntity.prototype = {
  getPrivateMember: function getPrivateMember() {
   return this._(key).getPrivateMember();
  },

  setPrivateMember: function setPrivateMember(test) {
   return this._(key).setPrivateMember(test);
  },
  publicMember: 1,
  clone: function clone() {
   var obj = {};
   for(var key in this) {
             obj[key] = this[key];
      }
   obj._(key, this._(key));
   return obj;
  }
 };
}({}));

var a = new JsDeepDive.PrototypedEntity(3);
a.setPrivateMember(2);
a.publicMember = 5;
console.log('a.privateMember: ' + a.getPrivateMember());
console.log('a.publicMember: ' + a.publicMember);
var b = a.clone();
console.log('b.privateMember: ' + b.getPrivateMember());
console.log('b.publicMember: ' + b.publicMember);
And the produced successful results:
a.privateMember: 2
a.publicMember: 5
b.privateMember: 2
b.publicMember: 5 
Hope you found it helpful and use this pattern in the future.
Sunday, July 27, 2014

JavaScript Builder Design Pattern


Today I would like to continue the series about design patterns we started with Factory Patterns in JavaScript and talk about the Builder pattern. For some reason it's being left behind in any design pattern usage in JavaScript. Maybe it was correct in the front end domain, but surely not in Node.js.

Builder pattern separates the construction of a complex object from its representation so that the same construction process can create different representations. The Builder pattern is based on Directors and Builders. Any number of Builder classes can conform to an IBuilder interface, and they can be called by a director to produce a product according to specification. The builders supply parts that the Product objects accumulate until the director is finished with the job. I'll be using the example from the factory pattern article to emphasize the differences between the patterns. Consider the class diagram for the Builder pattern:


And the implementation:
function FastCPU() {
    this.performOperation = function() {
        console.log("Operation will perform quickly");
    }
}
function SlowCPU() {
    this.performOperation = function() {
        console.log("Operation will perform slowly");
    }
}
 
function ExpensiveMotherBoard() {
    this.storeData = function() {
        console.log("There is a lot of RAM to store the data");
    }
}
 
function CheapMotherBoard() {
    this.storeData = function() {
        console.log("Little RAM. Swap file is used");
    }
}
 
function HighBudgetMachineBuilder() {
    this.getCPU = function() { return new FastCPU(); }
    this.getMotherBoard = function() {
     return new ExpensiveMotherBoard();
    }
}
 
function LowBudgetMachineBuilder() {
    this.getCPU = function() { return new SlowCPU(); }
    this.getMotherBoard = function() {
     return new CheapMotherBoard();
    }
}

function Director() {
    this.assembleMachine = function(builder) {
        var cpu = builder.getCPU(), 
        board = builder.getMotherBoard();
        return {
            cpu: cpu,
            board: board,
            test: function test() {
                this.cpu.performOperation();
                this.board.storeData();
            }
        }
    }
}
 
var director = new Director(),
    highBuilder = new HighBudgetMachineBuilder(),
    lowBuilder = new LowBudgetMachineBuilder(),
    highMachine = director.assembleMachine(highBuilder);
    lowMachine = director.assembleMachine(lowBuilder);
highMachine.test();
lowMachine.test();
We've added the director which assembles the machine. The client on the other hand, is not aware of the process of assembling the machines. It only uses the Director's method to do so.

The Builder and Abstract Factory patterns are similar in that they both look at construction at an abstract level. However, the Builder pattern is concerned with how a single object is made upby the different factories, whereas the Abstract Factory pattern is concerned with what products are made. The Builder pattern abstracts the algorithm for construction by including the concept of a director. The director is responsible for itemizing the steps and calls on builders to fulfill them. Directors do not have to conform to an interface.
Sunday, June 29, 2014

JavaScript Factory Patterns


Since June has 5 Sundays in it, today I will write a bonus article :) Following our last week's article about Publish and Subscribe Pattern with Postal.js, I'd like to broaden the topic talking about design patterns. The design patterns from the Gang of Four book offer solutions to common problems related to the object-oriented software design. It has been in use for decades and implemented in all server side languages. It's time we use them with JavaScript and start to write some piece of decent code. I'll be writing a series of articles covering all of them. As in the book, we'll be starting with creational patterns and cover both Abstract Factory and Factory Method patterns.

Abstract classes and interfaces enforce consistent interfaces in derived classes. In JavaScript we must ensure this consistency ourselves by making sure that each 'concrete' object has the same interface definition (i.e. properties and methods) as the others.

Abstract Factory Pattern


The Abstract Factory Pattern provides an interface for creating specific factories of dependent objects without specifying their concrete class.  Have a look at the illustration, depicting the pattern using UML.


Observe how Client is only aware of IMotherBoard and ICPU interfaces. The concrete factory responsible for creating the instances implementing these interfaces is also unknown. In JavaScript we don't have interfaces, but it doesn't mean that we cannot use the design pattern. Behold:
function FastCPU() {
    this.performOperation = function() {
        console.log("Operation will perform quickly");
    }
}
function SlowCPU() {
    this.performOperation = function() {
        console.log("Operation will perform slowly");
    }
}

function ExpensiveMotherBoard() {
    this.storeData = function() {
        console.log("There is a lot of RAM to store the data");
    }
}

function CheapMotherBoard() {
    this.storeData = function() {
        console.log("Little RAM. Swap file is used");
    }
}

function HighBudgetMachine() {
    this.getCPU = function() { return new FastCPU(); }
    this.getMotherBoard = function() {
     return new ExpensiveMotherBoard();
    }
}

function LowBudgetMachine() {
    this.getCPU = function() { return new SlowCPU(); }
    this.getMotherBoard = function() {
     return new CheapMotherBoard();
    }
}
All our classes implement the appropriate "ghost" interfaces. Now let's build our client:
function Client() {
 this.assembleMachine = function(factory) {
  var cpu = factory.getCPU(), 
   board = factory.getMotherBoard();
  // test the machine
  cpu.performOperation();
  board.storeData();
 }
}

var client = new Client();
client.assembleMachine(new HighBudgetMachine());
The output of course will be:
Operation will perform quickly
There is a lot of RAM to store the data 

Factory Method Pattern


The Factory Method pattern is a way of creating objects, but letting subclasses decide exactly which class to instantiate. Various subclasses might implement the interface; the Factory Method instantiates the appropriate subclass based on information supplied by the client or extracted from the current state. Please review the illustration below and the involved entities. Here we have interface ISorter, which defines common behaviour of our implementing classes, BubbleSorter and MergeSorterClient uses our factory Creator, which instantiates appropriate class.


Now in JavaScript:
function BubbleSorter() {
   this.sort = function (arr) {
        return "product A";
    }
}

function MergeSorter() {
   this.sort = function (arr) {
        return "product B";
    }
}

function Creator() {
    this.create = function(num) {
        if (num % 2 === 0) {
            return new BubbleSorter();
        }
        return new MergeSorter();
    }
}

var i, product, c = new Creator();
for (i = 0; i < 2; i += 1) {
    sorter = c.create(i);
    console.log(sorter.sort([5,2,7,3]));
}
Which produces the results:
bubble sorted
merge sorted

Conslusion


In Abstract Factory pattern, client is unaware of the specific factory used to instantiate the needed class, where as in Factory Method, a known factory is used.

Next time we'll continue our discussion about JavaScript design patterns and will cover additional creational patterns.

Sunday, June 22, 2014

Publish-Subscribe Pattern with Postal.js


Last week we talked about testing JavaScript Testing with Jasmine and today I'd like to continue our conversation about testing rather from different angle - separation of concerns. Once the code slips developers' fingers, it is hard to find time and strength to rewrite, it making it more testable. What works, may never be rewritten, sounds a bit like Iron island refrain What is dead, may never die :) Hmm - sorry for that! Nearly all today's applications have some calls to somewhere to retrieve the data. Front side retrieves from the server. Server side retrieves from services or database. Some manipulate it, others just format it and present as it is. Take a look at the following examples:
function someLogic() {
 $.get("ajax/test.html", function (data) {
  $(".result").html(data);
 }); 
}
function someLogic() {
 dataManager.getClients(function (err, data) {
  if (!err) {
   doSomething(data);
  }  
 }); 
}
How can you test it? First of all the server is needed to send the data. Secondly the data should always be the same to write our test specs correctly. Surely both are achievable, however wouldn't it be great if you could write the code in a way it's both clear and testable. This is where publish–subscribe pattern shines or pub/sub. Following the pattern ensures that your data receivers, or  subscribers, are totally separated from data producers, or publishers. The concept is represented in the following illustration:


A publisher observes the bus and when an event of interest is observed, a notification is created and sent to the notification engine. The notification is then matched against the subscribers that have expressed interest in the notification and prepared for the delivery. This model separates the management of the subscriptions, the matching process and the final delivery to the subscribers. There are currently two JavaScript libraries, which implement this pattern: Postal.js and Amplify.js. Since Amplify.js doesn't support server side programming and in the front side domain, Postal.js offers much more extensibility, we'll be focusing our conversation of Postal.js only.

Postal.js


Postal.js is an in-memory message bus - very loosely inspired by AMQP - written in JavaScript. Postal.js runs in the browser, or on the server using node.js. It takes the familiar "eventing-style" paradigm (of which most JavaScript developers are familiar) and extends it by providing "broker" and subscriber implementations, which are more sophisticated than what you typically find in simple event delegation.

In order to start working with the library, you should also add a reference to ConduitJS, since it's dependent on it. At first we need to create a channel, through which your messages will flow. The beauty of Postal.js is your ability to create named channels and separate completely your service buses by domains. If you don't need this ability, just create a default one without passing any name. Having our channel in place, we can subscribe to the events of interest and publish data to it. We called our event name.change, however you can call yours as you like. The dot separation though will come useful in the future.
var channel = postal.channel();
// subscribe to 'name.change' topics
var subscriber = channel.subscribe("name.change", function (data) {
 $("#example1").html("Name: " + data.name);
});
// And someone publishes a name change:
channel.publish("name.change", { name : "Dr. Who" });
// To unsubscribe, you:
subscriber.unsubscribe();
The data will flow through Postal's engine and be delivered to all the subscribers. The example present was rather dull, don't you agree? Let's spice it up by subscribing to change event of any object. We'll use the dot convention presented earlier and subscribe to event following the pattern *.change.
var subscriber = channel.subscribe("*.changed", function (data) {
 var i = $("
  • " + data.type + " -> " + data.value + "
  • "); i.appendTo("#example2"); } ); channel.publish("name.changed", {type: "Name", value: "John"}); channel.publish("country.changed",{type: "Country", value: "USA"}); subscriber.unsubscribe();
    As you can see both name.changed and country.changed are caught now. The pattern can be changed to name.*, which will catch all events related to name object like name.init or name.change. Postal.js supports additional patterns, have a look at their documentation to learn more.

    As said before, there are a lot of plugins written for Postal.js, making this library insanely useful. The most prominent are postal.when, providing even more targeted functionality to subscribers, and postal.federation delivering a framework to federate (or bridge) multiple instances of postal together, across various boundaries (frame/window, websocket, redis pub/sub, 0mq, etc.).

    We'll be talking more about messaging patterns in the future and various design patterns as well.
    Sunday, May 18, 2014

    Modular Design Patterns and Inheritance


    Last week we talked about JavaScript inheritance and if you recall we had talked about modular design patterns in JavaScript just a month ago. I would also like to talk about how to connect both modules and class inheritance. We've already discussed that modules are classes. So if we can link classes by inheritance relationship, the logical half of our brain suggests that we should be able to link modules as well. The logic prevails - we can.

    AMD and inheritance


    I'll be using the classes we defined in the inheritance article, Mammal and Dog, and create modules from them. Let's start with our super class:
    (function () {
        'use strict';
     
     define(function() {
      
      function Mammal() {
        this.age = 0;
        console.info("Mammal was born");
      }
       
      Mammal.prototype.grow = function() {
          this.age += 1;
          console.log("Mammal grows");
      };
    
      return Mammal;
     });
    }());
    
    Let's use it in our entry point JavaScript file. Just to remind you this file is declared in data-main attribute.
    (function () {
        'use strict';
     require(["Mammal"],
         function(Mammal) {
             var m = new Mammal();
             m.grow();
         }
       );
    })();
    
    Now it's time to create our Dog module. Since it needs Mammal for the inheritance, we'll list it in our dependency list. The implementation remains the same.
    (function () {
        'use strict';
     define(["Mammal"],
         function(Mammal) {
             function Dog(name) {
         this.name = name;
         Mammal.call(this);
       }
    
       Dog.prototype.grow=function(){ 
         this._super.grow.call(this);
         this.age =+ 1; 
         console.log('Dog grows');
       }
        
       Dog.prototype = Object.create(Mammal.prototype);
       Dog.prototype.constructor = Dog;
       Dog.prototype._super = Mammal.prototype;
         
       return Dog;
         });
    })();
    
    And of course update our main file to see if it works:
    (function () {
        'use strict';
     require(["Mammal", "Dog"],
         function(Mammal, Dog) {
             var m = new Mammal(), d = new Dog('Rocky');
       m.grow();
       d.grow();
         }
       );
    })();
    

    CommonJS and inheritance


    As you recall modules should be defined using the CommonJS syntax if you want to use them in Node.js.
    (function () {
        'use strict';
     
     function Mammal() {
       this.age = 0;
       console.info("Mammal was born");
     }
      
     Mammal.prototype.grow = function() {
         this.age += 1;
         console.log("Mammal grows");
     };
    
     module.exports = Mammal;
    }());
    
    
    As you can see we removed define method call and replaced return with module.exports.
    (function () {
        'use strict';
     
     var Mammal = require('Mammal');
    
        function Dog(name) {
       this.name = name;
       Mammal.call(this);
     }
    
     Dog.prototype.grow=function(){ 
       this._super.grow.call(this);
       this.age =+ 1; 
       console.log('Dog grows');
     }
      
     Dog.prototype = Object.create(Mammal.prototype);
     Dog.prototype.constructor = Dog;
     Dog.prototype._super = Mammal.prototype;
    
     module.exports = Dog;
    })();
    
    Here instead of listing the dependencies, we just require the Mammal class in our Dog definition.
    Sunday, April 27, 2014

    Modular Design Patterns in JavaScript


    Last week we've discussed how to create classes and namespaces in JavaScript. For those who missed it, you can read it here. There is however something else you need to know regarding the topic, which is modules.

    Modules


    When we say an application is modular, we generally mean it's composed of a set of highly decoupled, distinct pieces of functionality stored in modules. Module can and are implemented using classes, which we already know how to define. So what is the problem? When you try to build a complex piece of software, you end up with hundreds of classes. All of them somehow interact with one another and since JavaScript is not compiled, your job is to reference and load these classes in a correct order. This is why module loaders specification was invented - the most prominent of which are CommonJS and AMD.

    CommonJS


    Currently, CommonJS is a de facto standard. Many third-party vendors are making modules or module-load systems according to the CommonJS module specification. Node.js is a typical project that complies with the specification. CommonJS is a voluntary working group organized to use JavaScript not only in browser, but also in server-side and desktop applications.

    Definition


    If you're are Node.js developer, you've already used CommonJS syntax numerous times, without knowing it. There are other CommonJS implementation, however since Node.js is the most popular and wide spread technology, I'll use it in my examples. Recall our JsDeepDive.Common.Utils class from the previous post. Let's create a module from it using CommonJS syntax:
    (function () {
     'use strict';
    
     var Utils = function () {
      var privateMember = 1,
      privateFuncA = function privateFuncA() {
       return 'privateFuncA';
      },
    
      privateFuncB = function privateFuncB(test) {
       return test === privateMember;
      },
    
      privateFuncC = function privateFuncC(test) {
       if (privateFuncB(test)) {
        return 'test passed';
       } else {
        return 'test failed';
       }
      };
    
      return {
       publicFuncA: privateFuncA,
       privateFuncC: privateFuncC
      };
     }();
    
     module.exports = Utils;
    }());
    
    Then in another file you can load the module using require command like this:
    var Utils = require('./Utils.js');
    console.log(Utils.publicFuncA());
    
    Notice that we wrote the full path of our module file. This can be avoided by packing the module and creating package.json.

    You can load other packages within your definition - all of them will be loaded once needed. Remember that Node.js loads modules synchronously, so if your module requires prolonged initialization running during the require call, make sure to preload it before you use it. Also in Node.js, the module location is the namespace, so there's no need to namespace in the code as you've described.

    AMD


    AMD has separated itself from CommonJS production group, as it failed to reach an agreement in discussions with about using JavaScript module in an asynchronous situation. CommonJS created JavaScript as part of an effort to retrieve it outside of browsers; thus, could not generate agreement with AMD, which was focused on operation within browsers. According to Require.js site, which is the leading AMD implementation:

    It is an improvement over CommonJS modules because:
    • It works better in the browser, it has the least amount of gotchas. Other approaches have problems with debugging, cross-domain/CDN usage, file:// usage and the need for server-specific tooling.
    • Defines a way to include multiple modules in one file. In CommonJS terms, the term for this is a "transport format", and that group has not agreed on a transport format.
    • Allows setting a function as the return value. This is really useful for constructor functions. In CommonJS this is more awkward, always having to set a property on the exports object. Node supports module.exports = function () {}, but that is not part of a CommonJS spec.

    Definition


    Since AMD focuses on asynchronous module loading, it urges you to list all the dependencies in the definition statement.
    (function () {
     'use strict';
     
     define('Utils', ['jquery','underscore'], function($, _) {
      
      var privateMember = 1, 
      privateFuncA = function privateFuncA() {
       return 'privateFuncA';
      },
      
      privateFuncB = function privateFuncB(test) {
       return test === privateMember;
      },
      
      privateFuncC = function privateFuncC(test) {
       if (privateFuncB(test)) {
        return 'test passed';
       } else {
        return 'test failed';
       }
      };
    
      return {
       publicFuncA: privateFuncA,
       privateFuncC: privateFuncC
      };
     });
    }());
    
    Here we defined the Utils module, which depends upon JQuery and Underscore modules. If your module doesn't have any dependencies, you may omit the second parameter. You may also omit the first parameter, the name, which will make the module even more portable. It allows a developer to place the module in a different path to give it a different ID/name. The AMD loader will give the module an ID based on how it is referenced by other scripts.

    Firstly we need to configure our starting point. Notice that our main script was placed in data-main attribute and not as a source. This way we load Require.js first and it will take care of loading our main script.
    <script data-main="src/main.js" src="src/require.js"></script>
    
    Then inside our main, we configure where each package resides. This way Require.js will know where to look for definitions of Underscore, jQuery and eventually Utils. We do this with help of requirejs.config method.
    require.config({
        baseUrl: 'js/lib',
        paths: {
            jquery: 'jquery-1.9.0'
        }
    });
    
    The left side is the module ID and the right side is the path to the jQuery file, relative to baseUrl. Also, the path should NOT include the '.js' file extension.This example is using jQuery 1.9.0 located at js/lib/jquery-1.9.0.js, relative to the HTML page.

    Non AMD libraries

    You can also configure the dependencies, exports, and custom initialization for older, traditional "browser globals" scripts that do not use define() to declare the dependencies and set a module value. You do this with shim method. You can see the example of it's usage on Require.js site in the shim section.

    Universal module


    Someday you will want to create a module, which is both accessible in browser and server side environments. Require.js supports server side loading, providing CommonJS wrapper, however I wouldn't suggest you to follow this slippery road. Since nearly all Node.js developers don't use Require.js, they won't be able to use your beautiful module. However if you don't care about publicity and won't be sharing your work, you may try to unify your module creating and go only with Require.js.

    If you'd like to make your module accessible from both Require.js and Node.js using CommonJS syntax, here is how you can do it:
    (function () {
        'use strict';
    
     var Utils = function () {
      .....
     }();
    
     if (typeof define === 'function' && define.amd) {
         // Publish as AMD module
         define(function() {return Utils;});
     } else if (typeof(module) != 'undefined' && module.exports) {
         // Publish as node.js module
      module.exports = Utils;
     } else {
      // Publish as global (in browsers)
      window.Utils = Utils;
     }
    }());
    
    Basically we check for appropriate methods and act accordingly.