Design patterns in Javascript Part 1

Today we wanna see how apply three design patterns in javascript.

Singleton

 Singleton is one of the most used patterns, the idea is have a class with only one instance (or a limited number of instances). But better I copy the definition from Wikipedia."The singleton pattern is a design pattern used to implement the mathematical concept of a singleton, by restricting the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects (say, five)."

I can't think about an app wich doesn't uses this pattern.

function MySingleton(){

	this.doStuff=function(){

		console.log("Hello World!");

	}

}

MySingleton.instance=null;

MySingleton.getInstance=function(){

	if(this.instance==null){

		this.instance=new MySingleton();

	}

	return this.instance;

}

Decorator

This pattern is widely used in javascript, the idea is add data or behavior dynamically to an existing object. For example the framework jQuery use this pattern all the time. In this example we have a hamburger and we need to calculate the cost of all differente combination of ingredients, with this pattern we can do this without change the code of our original object.

// Class to be decorated
function Hamburger() {
    this.cost = function() {
	return 1;
    };
}
 
// Decorators
function Cheddar(hamburger) {
    this.cost = function() {
	return hamburger.cost() + 1;
    };	
}
 
function Tomato(hamburger) {
    this.cost = function() {
	return hamburger.cost() + 0.5;
    };
}
 
function Lettuce(hamburger) {
    this.cost = function() {
	return hamburger.cost() + 0.3;
    };
}

console.log("Prices:");
console.log("Hamburger: "+new Hamburger().cost());
console.log("Hamburger with cheese: "+new Cheddar(new Hamburger()).cost());
console.log("Hamburger with tomato: "+new Tomato(new Hamburger()).cost());
console.log("Hamburger with lettuce: "+new Lettuce(new Hamburger()).cost());
console.log("Hamburger with all ingredients: "+new Cheddar(new Tomato(new Lettuce(new Hamburger()))).cost());

 

Proxy

This is other pattern which you want to use all the time. The proxy pattern in javascript is used for change the functionality of a existing method or function. In this example we want to see how change an existing "Hello World" function.

var helloWorld=function(){
	return "Hello World";
}
var oldHelloWorld=helloWorld;
helloWorld=function(name){
	return oldHelloWorld()+" my name is "+name;
}
console.log(helloWorld("Roque"));

 

In the next post we want to see other patterns.
Good luck!

:wq 

Author

Magento Specialist