Design Patterns
Factory & Singleton
Two essential creational patterns. Factory functions centralise object construction and decouple callers from implementation. The Singleton pattern ensures exactly one shared instance — perfect for configs, loggers, and connection pools.
What are the factory and singleton patterns?
A factory is a function that creates and returns objects, letting you hide setup details and choose what to build based on its arguments, without new or classes. A singleton guarantees only one instance of something exists, such as one database connection or one config object. In JavaScript, an ES module that exports an instance is already a singleton.
// Factory
function createUser(name, role = "student") {
return { name, role, greet: () => `Hi, ${name}` };
}
// Singleton via module
// db.js
export const db = connect(process.env.DATABASE_URL); // created oncePattern Comparison
| Pattern | Purpose | Returns | # Instances | Use When |
|---|---|---|---|---|
| Factory Function | Centralise object creation | New object each call | Many | Need private state, avoid new |
| Static Factory Method | Named, semantic constructors | New instance | Many | Class with multiple creation modes |
| Abstract Factory | Families of related objects | Set of related objects | Many | Swap whole UI theme / platform |
| Singleton | Single shared instance | Always same object | One | Config, logger, DB pool, cache |
| Object Pool | Reuse pre-created objects | Existing or new object | Fixed max | DB connections, worker threads |
Common Pitfalls
Overusing Singleton — becomes global mutable state, makes testing hard (can't reset between tests)
Use dependency injection instead. Pass config/logger as parameters. Keep singletons for truly global concerns (logger, env config).
Factory function that does too much — construction + validation + side effects all in one
Keep factory functions focused: construct and return. Use a builder pattern or separate service for complex validation.
Sharing mutable objects from a factory (all callers mutate same arrays/objects)
Create fresh arrays/objects in each factory call: const _items = []; not sharing a shared array.
Singleton that can't be reset — impossible to test in isolation
Add a reset() method to singletons. In tests, call reset() in beforeEach. Or use ES module mock reset in Jest.
Interactive Demo
Code Editor
<pre id="out"></pre>Preview
Factory and Singleton Patterns: summary
Key points
- Factories pair well with closures for private state.
- Singletons are global state in disguise; they make testing harder.
- Use dependency injection (pass instances in) when you need to swap implementations.
Frequently asked questions
›Factory function or class?
Both work. Factories avoid this and new pitfalls and make privacy easy; classes give you instanceof and slightly better performance for many instances.