The Factory pattern
- JavaScript course
- Expert
- Lesson 3/63
- 5 min
Learn the pattern that moves object creation into a factory function.
The Factory pattern
The Factory pattern moves object creation logic into a separate factory function. The calling code does not know which object is produced; it just passes a parameter and gets a result.
This makes code more flexible. To add a new object type you change only the factory; callers stay the same.
Writing a function that produces objects instead of using a class is common in JS.
Factory function example
The factory below produces button objects based on the type parameter. The caller just writes createButton('primary', 'Save'); production details stay inside the factory.
function createButton(type, label) {
return { label: label, kind: type };
}This pattern is especially useful when there are many similar object types.
Practice createButton factory
Write a factory function createButton(type, label). The returned object should have a label property equal to label and a render() method that returns label. If type is 'primary', set button.kind = 'primary'. Finally return the button object.
Starter code
// write the createButton factory function
// takes type and label parameters
// returns an object with label and render()Sample solution
function createButton(type, label) {
const button = {
label: label,
render() {
return label;
}
};
if (type === 'primary') {
button.kind = 'primary';
}
return button;
}Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What advantage does the Factory pattern provide?
- Sort objects faster
- Auto-clean memory
- Separate object creation from the caller Correct answer
- Inherit classes
Explanation: Factory moves creation logic into a factory function.
2 Complete the factory return
function createButton(label) {
return { label: label, ____() { return label; } };
}
function createButton(label) {
return { label: label, render() { return label; } };
}
Explanation: The render() method returns the label.
3 Match the Factory concepts
| Term | Meaning |
|---|---|
Factory |
Separates object creation |
createButton() |
Factory function |
type parameter |
Decides which type to make |
return {} |
Returns a new object |