Hiprup

What is the factory pattern in JavaScript?

A factory is a function that creates and returns objects, hiding the construction details from the caller.

  • No new — call the factory like a normal function; it builds and returns the object.

  • Flexibility — can return different object types based on input.

Useful when creating objects involves logic, or you want to avoid exposing constructors and the new keyword.

// Factory function
function createNotification(type, message) {
  const notifications = {
    email: { type: 'email', send: () => sendEmail(message), icon: '📧' },
    sms: { type: 'sms', send: () => sendSMS(message), icon: '📱' },
    push: { type: 'push', send: () => sendPush(message), icon: '🔔' }
  };

  if (!notifications[type]) throw new Error(`Unknown type: ${type}`);
  return notifications[type];
}

// Usage — consumer does not know implementation details
const notification = createNotification('email', 'Hello!');
notification.send();

// Class-based factory
class UserFactory {
  static create(role, data) {
    switch (role) {
      case 'admin': return new AdminUser(data);
      case 'editor': return new EditorUser(data);
      default: return new BasicUser(data);
    }
  }
}

const user = UserFactory.create('admin', { name: 'John' });

createNotification returns different objects based on the type parameter. The consumer calls send() without knowing the underlying implementation.

UserFactory.create returns different user classes based on role. Both centralize creation logic — adding a new type requires changing only the factory, not the consumers.

Show the factory returning different objects based on input. The key benefit: adding new types requires only changing the factory, not all consumers.

Compare to directly using new (tight coupling). Both function and class-based approaches work in JS.

What is the factory pattern in JavaScript? | Hiprup