Thursday, May 26, 2011

javascript design patterns - Factory

Factory pattern is used to create objects. The most normal implementation is a static method of a class(object in javascript). 

When to use Factory Pattern?
When you need to create objects that implement same interface, and you don't know(you don't need to know, and you shouldn't know) the specific class type/object type at compile time, factory pattern is the solution for you.

Suppose you have a Car interface:
//code below is not a correct interface implementation in javascript, 
//but just suppose it is an interface
var Car = function(){};
Car.prototype.run = function(){};

//suppose we have an extend() method doing the inheritance 
var Mazda = function(){};
extend(Mazda, Car);

var Ford = function(){};
extend(Ford, Car);

//Now, we need a factory method to make cars for clients.
Car.factory = function(name) {
    //here is the condition to check which car should be made.
    //usually is a switch/case, but here i simply use if else
    if (name === 'ford') {
        return new Ford();
    }
    if (name === 'mazda') {
        return new Mazda();
    }   
}

//i want a car!
var myCar = Car.factory('mazda');
//run!!!!
myCar.run();

No comments: