Friday, January 18, 2008

Singleton Pattern in Java Script using Lazy Instantiation

Singleton pattern provide a way group of code and logical unit can access through a single instance. In JavaScript it can be used for namespacing, which reduce number of global variable in your class. It can also use encapsulate browser different through a technique known as branching.

Singleton patten example through java script



var StringUtil = window.StringUtil || {}

StringUtil.DataParser = (function(){

var uniqueInstance;

function constructor(){

var whiteSpaceReges = /\s+/;

function stropWhiteSpace(str){
return str.replace(whiteSpaceReges,'');
}

function stringSplit(str, delimiter){
return str.split(delimiter);
}

this.stringToArray = function(str, delimiter, stripWS){
if(stripWS){
str = stropWhiteSpace(str);
}
var outputArray = stringSplit(str, delimiter);
return outputArray;
}
}

return {
getInstance: function(){
if(!uniqueInstance){
uniqueInstance = new constructor();
}
return uniqueInstance;
}
}
})();




Run the code:
var testStr = 'Hello , World, Test ';
var output = StringUtil.DataParser.getInstance().stringToArray(testStr,',',false);
output.length -> 3
Implement Interface in JavaScript

An interface provide a way what the behavior of the object should have mean what the method of the object. But it does not say how those method and behavior should be implemented. This allow group of object have same behavior.

Advantage of using interface in Java Script
Establishment interfaces are self documenting and promote re usability. An interface tell programmer what method must be implement which make user to use and easier to find out error and unit test.
Disadvantage of using interfaced
Java Script is extremely expressive language. Using interface its behave some thing like strict typing. There is no built in support or keyword like interface so it is not easy to implements interface in Java Script. Every thing need to implements manually. Using interface implementation in Java Script will create a performance hot, due in the part of having another mehtod invocation.

In complex map application there are many implementation and every one ensure all have implement all method that need the application.

function displayRoute(mapInstance) {
Interface.ensureImplements(mapInstace, DynamicMap);
mapInstance.centerOnPoint(12, 34);
mapInstance.zoom(5);
mapInstance.draw();
...
}

If any one want to use the display Route function then he/her must implement all the method like centerOnPoint, zoom and draw


Step by Step Interface implementation:

Simple Student class,
In Java:


interface IStudent{
void setName(String name)
String getName();
}

public class Student implements IStudent{
private String name
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}

}


In Java Script

1. Create Interface function that store the name of the implementation and name of the method.




var Interface = function(name, methods) {
if(arguments.length != 2) {
// alert("Expected two argument..");
throw new Error("Interface constructor called with " + arguments.length
+ "arguments, but expected exactly 2.");
}

this.name = name;
this.methods = []; //store the mehod name

for(var i = 0, len = methods.length; i <>


2. Create the static method of the Interface ensure the implementation.


Interface.ensureImplements = function(object) {

if(arguments.length < i =" 1," len =" arguments.length;" interface_ =" arguments[i];" j =" 0," methodslen =" interface_.methods.length;" method =" interface_.methods[j];">


3. Create Interface variable

var IStudent = new Interface('Student1',['setName','getName']);

var Student = function(){ };

Student.prototype.setName = function(name){
this.name = name;
}

Student.prototype.getName = function(){
return this.name;
}

function studentOperation(student){
Interface.ensureImplements(student, IStudent);
student.setName('Test Student1');
alert(student.getName());
}

5. Use the interface



function studentOperation(student){
Interface.ensureImplements(student, IStudent); // Must check the
student.setName('Test Student1');
alert(student.getName());
}

Thursday, January 17, 2008

Mixin in Java Script

There are many way to reuse code without strict inheritance, Mixin is the one of way. In practice it goes something like that any one create class that contain general purpose methods then use it to augment other classes. Those class with the general purpose method are called Mixin. Mixin implementation in JavaScript

1. First create a Person class

function Person(name){
this.name = name;
}
Person.prototype.getName = function(){
return this.name
}

2. Then create another class

function Author(name, books){
Person.call(this, name); // super class constructor call here
this.books = books
}
Author.prototype.getBooks = function(){
return this.books
}

3. Set the inheritance property

Author.prototype = new Person(); // the

4. Create the instance of the Author

var author = new Author('Ross Harmes', ['JavaScript Design Patterns']);
author.getName() ///It will print the author name of Ross Harmess

5. Now create Mixin class

function Mixin(){
};

Mixin.prototype.serialize = function() { //common method
return "Hello from Mixin"
}


//set the mixin proprty
function augment(receivingClass, givingClass){

if(arguments[2]){
for(var i = 0, len = arguments.length; i < len; i++){
receivingClass.prototype[arguments[i]] = givingClass.prototype[arguments[i]];
}
}else{
for(methodName in givingClass.prototype){
if(!receivingClass.prototype[methodName]){
receivingClass.prototype[methodName] = givingClass.prototype[methodName];
}
}
}
}

6. Call Mixin proprty

augment(Author, Mixin)
var author = new Author('testName',[''testBookName]);
var serializeStr = author.serialize(); //Result: 'Hello from mixin'