Factory

Creates an instance of several derived classes.

  • Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

  • loose coupling by eliminating the need to bind application specific classes into code.

  • It is just a fancy name for a method that instantiates an object.

  • Its job is to create an object.

  • Real time EX: Nescafe machine - press button to get the respective output.

EX:
var fromPrototype = function(prototype, object) {
    var newObject = Object.create(prototype);
    for (var prop in object) {
        if (object.hasOwnProperty(prop)) {
            newObject[prop] = object[prop];
        }
    }
  return newObject;
};

// Define the Pizza product
var Pizza = {
    description: 'Plain Generic Pizza'
};

// And the basic PizzaStore
var PizzaStore = {
    createPizza: function(type) {
        if (type == 'cheese') {
            return fromPrototype(Pizza, {
                description: 'Cheesy, Generic Pizza'
            });
        } else if (type == 'veggie') {
            return fromPrototype(Pizza, {
                description: 'Veggie, Generic Pizza'
            });
        }
    }
};

var ChicagoPizzaStore = fromPrototype(PizzaStore, {
    createPizza: function(type) {
        if (type == 'cheese') {
            return fromPrototype(Pizza, {
                description: 'Cheesy, Deep-dish Chicago Pizza'
            });
        } else if (type == 'veggie') {
            return fromPrototype(Pizza, {
                description: 'Veggie, Deep-dish Chicago Pizza'
            });
        }
    }
});

var CaliforniaPizzaStore = fromPrototype(PizzaStore, {
    createPizza: function(type) {
        if (type == 'cheese') {
            return fromPrototype(Pizza, {
                description: 'Cheesy, Tasty California Pizza'
            });
        } else if (type == 'veggie') {
            return fromPrototype(Pizza, {
                description: 'Veggie, Tasty California Pizza'
            });
        }
    }
});

// Elsewhere in our app...
var chicagoStore = Object.create(ChicagoPizzaStore);
var pizza = chicagoStore.createPizza('veggie');
console.log(pizza.description); // returns 'Veggie, Deep-dish Chicago Pizza'

Last updated