The Factory pattern
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.
Exercise 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.
Show example solution
label, render() { return label; } }, if type is 'primary' set button.kind = 'primary', finally return button.
Example solution:
function createButton(type, label) {
const button = {
label: label,
render() {
return label;
}
};
if (type === 'primary') {
button.kind = 'primary';
}
return button;
}
Test yourself
-
What advantage does the Factory pattern provide?
- Sort objects faster
- Auto-clean memory
- Separate object creation from the caller
- Inherit classes
Show answer
Separate object creation from the caller — Correct! Factory moves creation logic into a factory function.
-
Complete the factory return
function createButton(label) { return { label: label, ____() { return label; } }; }Show answer
function createButton(label) { return { label: label, render() { return label; } }; } -
Match the Factory concepts
- Factory
- Separates object creation
- createButton()
- Factory function
- type parameter
- Decides which type to make
- return {}
- Returns a new object