Back to results for “Architecture”
Node.js › Architecture & Design Patterns

How is the Factory pattern commonly applied in Node.js applications, and what problem does it solve?

Intermediate

Answer

A factory function or factory class centralizes object creation logic behind a single function, hiding the specific class or configuration details from the calling code -- useful when object construction is conditional (different implementations based on environment or input) or complex enough that scattering 'new ClassName()' calls throughout the codebase would create tight coupling to specific implementations.
function createLogger(env) {
  if (env === 'production') return new JsonLogger();
  if (env === 'test') return new SilentLogger();
  return new ConsoleLogger();
}

const logger = createLogger(process.env.NODE_ENV);
Real-world example A multi-tenant SaaS application uses a factory function to construct the correct database adapter (PostgresAdapter, MySQLAdapter, or a mock TestAdapter) based on each tenant's configuration, so the rest of the application code interacts only with a common adapter interface without knowing which concrete class it received.

Common follow-ups: How does the Factory pattern relate to the Dependency Injection pattern -- are they complementary or competing approaches?;When does introducing a factory add unnecessary indirection for a genuinely simple case?