> For the complete documentation index, see [llms.txt](https://javascript-1.gitbook.io/design-pattern/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://javascript-1.gitbook.io/design-pattern/creational-design-patterns/factory.md).

# Factory

* 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.

![Factory Method](/files/-LoZtuSopiN4G078yI-R)

```javascript
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'
```
