As the name implies this pattern is used to create objects,

You can use it when you need to create an object without knowing the exact class, for example you want to create a Milk object but you don’t know if you need to create a ChocolateMilk or LowFatMilk classes.

You can also use it if you need to create pre configured classes where you need the same object several times only with some small configuration changes Now a few examples of the factory pattern implementation in JavaScript, the first example is the classic example of “pre configured” classes

1
2
3
4
5
6
7
8
9
10
11
12
13
var fooFactoryClass = function(){
    return{
        create : function(width, height){
            var obj = new fooClass();
            obj.setWidth(width);
            obj.setHeight(height);
            return obj;
        }
    };
};

var fooFactory = new fooFactoryClass();
var myFooClass = fooFactory.create(100,50);

This is a simple implementation where we constructed a factory class to return a fooClass object but with different configuration options.

The next example a different class is returned according to the options passed to the factory create method.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
var chocolateMilk = function(milk){
    return {
        name: "Chocolate Milk"
    };
};
var lowFatMilk = function(milk){
    return {
        name: "Low Fat Milk"
    };
};
var milkFactoryClass = function(){
    return{
        create: function(unknownMilkObject){
            switch(unknownMilkObject.color){
                case "brown":
                    return new chocolateMilk();
                    break;
                default:
                    return new lowFatMilk();
            }
        }
    };
};
var milkFactory = new milkFactoryClass();

var milkType = {
        color: "brown"
};
var milkObject = milkFactory.create(milkType);

console.log(milkObject.name);//outputs Chocolate Milk

The first two object create are the chocolate and low fat milk classes.

The factory method will inspect the color property and return a chocolateMilk or lowFatMilk class depending on the property value