JavaScript and TypeScript course ยท Module 9: Design Patterns and Architecture

Design Patterns in JavaScript/TypeScript - Module, Factory and Observer

20 min read ยท
In this lesson6

NOTE: Extended material - Study plan

This module contains very extensive educational material. You don't have to absorb everything at once! Here is a suggested learning order:

Stage 1 - Fundamentals (priority: high)

  • Module Pattern and Revealing Module Pattern
  • Factory Pattern
  • Observer Pattern
  • Singleton Pattern

Stage 2 - Architecture (priority: medium)

  • SOLID principles
  • Dependency Injection and the Event Bus

Stage 3 - Functional programming and state (priority: medium)

  • Pure functions, immutability, currying and composition
  • State management patterns: Flux, Event Sourcing, state machines

Stage 4 - Performance and practice (study as needed)

  • Code splitting, tree shaking and lazy loading
  • Bundle optimization
  • Event-driven architecture and the final project

Tips:

  • Absorb the material sequentially, section by section
  • After each pattern, take a break and practice it on your own
  • Return to more difficult topics after some time
  • Don't skip the fundamentals - they are key to understanding the rest
  • Advanced patterns can be studied as needed in projects

Remember: it's better to understand the basics well than to skim through everything superficially!


Just as ancient architects used proven construction patterns to build durable temples, modern programmers use design patterns to create solid, scalable code. In this lesson, we will learn four fundamental patterns: Module Pattern, Revealing Module Pattern, Factory Pattern, and Observer Pattern, which form the foundation of many modern JavaScript and TypeScript applications.

Module Pattern - Encapsulation and privacy

The Module Pattern is one of the most important patterns in JavaScript, allowing code encapsulation and the creation of private variables and methods. Before the introduction of ES6 modules, it was the main way to organize code into modules.

Classic Module Pattern implementation

// Example of a simple calculator module
const Calculator = (function() {
  // Private variables and functions
  let result = 0;

  function validateNumber(num) {
    if (typeof num !== 'number' || isNaN(num)) {
      throw new Error('The provided value is not a number');
    }
  }

  function logOperation(operation, num) {
    console.log(`Operation performed: ${operation} ${num}`);
  }

  // Public interface
  return {
    add: function(num) {
      validateNumber(num);
      result += num;
      logOperation('addition', num);
      return this;
    },

    subtract: function(num) {
      validateNumber(num);
      result -= num;
      logOperation('subtraction', num);
      return this;
    },

    multiply: function(num) {
      validateNumber(num);
      result *= num;
      logOperation('multiplication', num);
      return this;
    },

    divide: function(num) {
      validateNumber(num);
      if (num === 0) {
        throw new Error('Cannot divide by zero');
      }
      result /= num;
      logOperation('division', num);
      return this;
    },

    getResult: function() {
      return result;
    },

    reset: function() {
      result = 0;
      console.log('Calculator has been reset');
      return this;
    }
  };
})();

// Usage
Calculator
  .add(10)
  .multiply(2)
  .subtract(5)
  .divide(3);

console.log(Calculator.getResult()); // 5

Module Pattern with parameters

// Module for managing application state
const StateManager = (function(initialState = {}) {
  // Private state
  let state = { ...initialState };
  let listeners = [];

  // Private helper functions
  function deepClone(obj) {
    return JSON.parse(JSON.stringify(obj));
  }

  function notifyListeners(action, newState) {
    listeners.forEach(listener => {
      if (typeof listener === 'function') {
        listener(action, deepClone(newState));
      }
    });
  }

  // Public interface
  return {
    getState: function(key) {
      if (key) {
        return deepClone(state[key]);
      }
      return deepClone(state);
    },

    setState: function(key, value) {
      const oldValue = state[key];
      state[key] = value;

      notifyListeners({
        type: 'STATE_CHANGED',
        key: key,
        oldValue: oldValue,
        newValue: value
      }, state);

      return this;
    },

    updateState: function(updates) {
      const oldState = deepClone(state);
      state = { ...state, ...updates };

      notifyListeners({
        type: 'STATE_UPDATED',
        oldState: oldState,
        newState: deepClone(state)
      }, state);

      return this;
    },

    subscribe: function(listener) {
      if (typeof listener === 'function') {
        listeners.push(listener);
      }

      // Return an unsubscribe function
      return function unsubscribe() {
        const index = listeners.indexOf(listener);
        if (index > -1) {
          listeners.splice(index, 1);
        }
      };
    },

    reset: function() {
      const oldState = deepClone(state);
      state = { ...initialState };

      notifyListeners({
        type: 'STATE_RESET',
        oldState: oldState
      }, state);

      return this;
    }
  };
})({ theme: 'light', language: 'pl' });

// Usage
const unsubscribe = StateManager.subscribe((action, newState) => {
  console.log('State has changed:', action);
});

StateManager
  .setState('user', { name: 'Jan', age: 30 })
  .updateState({ theme: 'dark', notifications: true });

Revealing Module Pattern - Improved encapsulation

The Revealing Module Pattern is an evolution of the Module Pattern that provides greater readability and better separation between private and public functions.

Basic Revealing Module Pattern implementation

// Module for managing products in a store
const ProductManager = (function() {
  // Private variables
  let products = [];
  let nextId = 1;

  // Private functions
  function generateId() {
    return nextId++;
  }

  function validateProduct(product) {
    if (!product.name || typeof product.name !== 'string') {
      throw new Error('Product name is required and must be a string');
    }

    if (!product.price || typeof product.price !== 'number' || product.price <= 0) {
      throw new Error('Product price must be a number greater than zero');
    }

    return true;
  }

  function findProductIndex(id) {
    return products.findIndex(product => product.id === id);
  }

  function sortProductsByPrice(ascending = true) {
    return products.slice().sort((a, b) => {
      return ascending ? a.price - b.price : b.price - a.price;
    });
  }

  function filterProductsByCategory(category) {
    return products.filter(product =>
      product.category && product.category.toLowerCase() === category.toLowerCase()
    );
  }

  // Public functions
  function addProduct(productData) {
    validateProduct(productData);

    const product = {
      id: generateId(),
      name: productData.name,
      price: productData.price,
      category: productData.category || 'uncategorized',
      description: productData.description || '',
      inStock: productData.inStock !== false,
      createdAt: new Date().toISOString()
    };

    products.push(product);
    console.log(`Product added: ${product.name}`);

    return product.id;
  }

  function removeProduct(id) {
    const index = findProductIndex(id);

    if (index === -1) {
      throw new Error(`Product with ID ${id} was not found`);
    }

    const removedProduct = products.splice(index, 1)[0];
    console.log(`Product removed: ${removedProduct.name}`);

    return removedProduct;
  }

  function updateProduct(id, updates) {
    const index = findProductIndex(id);

    if (index === -1) {
      throw new Error(`Product with ID ${id} was not found`);
    }

    const updatedProduct = { ...products[index], ...updates };
    validateProduct(updatedProduct);

    products[index] = updatedProduct;
    console.log(`Product updated: ${updatedProduct.name}`);

    return updatedProduct;
  }

  function getProduct(id) {
    const product = products.find(p => p.id === id);
    return product ? { ...product } : null;
  }

  function getAllProducts() {
    return products.map(product => ({ ...product }));
  }

  function getProductsByCategory(category) {
    return filterProductsByCategory(category).map(product => ({ ...product }));
  }

  function getProductsSortedByPrice(ascending = true) {
    return sortProductsByPrice(ascending).map(product => ({ ...product }));
  }

  function getProductCount() {
    return products.length;
  }

  function clearAllProducts() {
    const count = products.length;
    products = [];
    nextId = 1;
    console.log(`All products removed (${count})`);
  }

  // Revealing - exposing public methods
  return {
    add: addProduct,
    remove: removeProduct,
    update: updateProduct,
    get: getProduct,
    getAll: getAllProducts,
    getByCategory: getProductsByCategory,
    getSortedByPrice: getProductsSortedByPrice,
    count: getProductCount,
    clear: clearAllProducts
  };
})();

// Usage
const laptopId = ProductManager.add({
  name: 'Laptop Dell XPS 13',
  price: 4500,
  category: 'Electronics',
  description: 'High-quality ultrabook laptop'
});

const phoneId = ProductManager.add({
  name: 'iPhone 15 Pro',
  price: 5500,
  category: 'Electronics'
});

console.log('Electronics products:', ProductManager.getByCategory('Electronics'));
console.log('Sorted products:', ProductManager.getSortedByPrice());

TypeScript with Revealing Module Pattern

// Interfaces for better typing
interface User {
  id: number;
  email: string;
  name: string;
  role: 'admin' | 'user' | 'moderator';
  isActive: boolean;
  lastLogin?: Date;
}

interface UserCreateData {
  email: string;
  name: string;
  role?: User['role'];
}

interface UserUpdateData {
  name?: string;
  role?: User['role'];
  isActive?: boolean;
}

// User management module in TypeScript
const UserManager = (function(): {
  createUser: (userData: UserCreateData) => number;
  getUserById: (id: number) => User | null;
  updateUser: (id: number, updates: UserUpdateData) => User | null;
  deleteUser: (id: number) => boolean;
  getAllUsers: () => User[];
  getActiveUsers: () => User[];
  getUsersByRole: (role: User['role']) => User[];
  markUserLogin: (id: number) => boolean;
  getUserCount: () => number;
} {
  // Private variables
  let users: User[] = [];
  let nextId: number = 1;

  // Private functions
  function generateId(): number {
    return nextId++;
  }

  function validateEmail(email: string): boolean {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
  }

  function findUserIndex(id: number): number {
    return users.findIndex(user => user.id === id);
  }

  function isEmailTaken(email: string, excludeId?: number): boolean {
    return users.some(user =>
      user.email.toLowerCase() === email.toLowerCase() &&
      user.id !== excludeId
    );
  }

  function createUserObject(userData: UserCreateData): User {
    return {
      id: generateId(),
      email: userData.email.toLowerCase(),
      name: userData.name,
      role: userData.role || 'user',
      isActive: true,
      lastLogin: undefined
    };
  }

  // Public functions
  function createUser(userData: UserCreateData): number {
    if (!validateEmail(userData.email)) {
      throw new Error('Invalid email format');
    }

    if (isEmailTaken(userData.email)) {
      throw new Error('A user with this email already exists');
    }

    if (!userData.name || userData.name.trim().length < 2) {
      throw new Error('Username must be at least 2 characters long');
    }

    const user = createUserObject(userData);
    users.push(user);

    console.log(`User created: ${user.name} (${user.email})`);
    return user.id;
  }

  function getUserById(id: number): User | null {
    const user = users.find(u => u.id === id);
    return user ? { ...user } : null;
  }

  function updateUser(id: number, updates: UserUpdateData): User | null {
    const index = findUserIndex(id);

    if (index === -1) {
      return null;
    }

    const currentUser = users[index];
    const updatedUser: User = {
      ...currentUser,
      ...updates
    };

    if (updates.name && updates.name.trim().length < 2) {
      throw new Error('Username must be at least 2 characters long');
    }

    users[index] = updatedUser;
    console.log(`User updated: ${updatedUser.name}`);

    return { ...updatedUser };
  }

  function deleteUser(id: number): boolean {
    const index = findUserIndex(id);

    if (index === -1) {
      return false;
    }

    const deletedUser = users.splice(index, 1)[0];
    console.log(`User deleted: ${deletedUser.name}`);

    return true;
  }

  function getAllUsers(): User[] {
    return users.map(user => ({ ...user }));
  }

  function getActiveUsers(): User[] {
    return users.filter(user => user.isActive).map(user => ({ ...user }));
  }

  function getUsersByRole(role: User['role']): User[] {
    return users.filter(user => user.role === role).map(user => ({ ...user }));
  }

  function markUserLogin(id: number): boolean {
    const index = findUserIndex(id);

    if (index === -1) {
      return false;
    }

    users[index].lastLogin = new Date();
    return true;
  }

  function getUserCount(): number {
    return users.length;
  }

  // Revealing - exposing public methods
  return {
    createUser,
    getUserById,
    updateUser,
    deleteUser,
    getAllUsers,
    getActiveUsers,
    getUsersByRole,
    markUserLogin,
    getUserCount
  };
})();

// Usage with TypeScript
const adminId = UserManager.createUser({
  email: 'admin@example.com',
  name: 'Administrator',
  role: 'admin'
});

const userId = UserManager.createUser({
  email: 'user@example.com',
  name: 'Jan Kowalski'
});

console.log('Administrators:', UserManager.getUsersByRole('admin'));
console.log('Active users:', UserManager.getActiveUsers());

Factory Pattern - Creating objects

The Factory Pattern is a creational pattern that allows creating objects without specifying the concrete class of the object to be created. It is particularly useful when we have different types of objects with a similar structure.

Simple Factory Pattern

// Factory for creating different types of vehicles
class VehicleFactory {
  static createVehicle(type, options = {}) {
    switch (type.toLowerCase()) {
      case 'car':
        return new Car(options);
      case 'motorcycle':
        return new Motorcycle(options);
      case 'truck':
        return new Truck(options);
      case 'bicycle':
        return new Bicycle(options);
      default:
        throw new Error(`Unknown vehicle type: ${type}`);
    }
  }

  static getSupportedTypes() {
    return ['car', 'motorcycle', 'truck', 'bicycle'];
  }
}

// Base classes
class Vehicle {
  constructor(options = {}) {
    this.brand = options.brand || 'Unknown';
    this.model = options.model || 'Unknown';
    this.year = options.year || new Date().getFullYear();
    this.color = options.color || 'white';
    this.maxSpeed = options.maxSpeed || 0;
  }

  start() {
    console.log(`${this.brand} ${this.model} has been started`);
  }

  stop() {
    console.log(`${this.brand} ${this.model} has been stopped`);
  }

  getInfo() {
    return `${this.brand} ${this.model} (${this.year}) - ${this.color}`;
  }
}

class Car extends Vehicle {
  constructor(options = {}) {
    super(options);
    this.type = 'Car';
    this.doors = options.doors || 4;
    this.fuelType = options.fuelType || 'gasoline';
    this.transmission = options.transmission || 'manual';
  }

  openTrunk() {
    console.log('Trunk has been opened');
  }

  getDetails() {
    return `${this.getInfo()} - ${this.doors} doors, ${this.fuelType}, ${this.transmission}`;
  }
}

class Motorcycle extends Vehicle {
  constructor(options = {}) {
    super(options);
    this.type = 'Motorcycle';
    this.engineSize = options.engineSize || 125; // cc
    this.hasSidecar = options.hasSidecar || false;
  }

  wheelie() {
    console.log('Doing a wheelie!');
  }

  getDetails() {
    const sidecar = this.hasSidecar ? 'with sidecar' : 'without sidecar';
    return `${this.getInfo()} - ${this.engineSize}cc, ${sidecar}`;
  }
}

class Truck extends Vehicle {
  constructor(options = {}) {
    super(options);
    this.type = 'Truck';
    this.loadCapacity = options.loadCapacity || 1000; // kg
    this.trailerAttached = options.trailerAttached || false;
  }

  loadCargo(weight) {
    if (weight > this.loadCapacity) {
      console.log(`Cannot load ${weight}kg. Maximum capacity: ${this.loadCapacity}kg`);
      return false;
    }

    console.log(`Loaded ${weight}kg cargo`);
    return true;
  }

  getDetails() {
    const trailer = this.trailerAttached ? 'with trailer' : 'without trailer';
    return `${this.getInfo()} - capacity: ${this.loadCapacity}kg, ${trailer}`;
  }
}

class Bicycle extends Vehicle {
  constructor(options = {}) {
    super(options);
    this.type = 'Bicycle';
    this.gears = options.gears || 1;
    this.isElectric = options.isElectric || false;
    this.maxSpeed = options.maxSpeed || 25;
  }

  ringBell() {
    console.log('Ring ring!');
  }

  getDetails() {
    const electric = this.isElectric ? 'electric' : 'traditional';
    return `${this.getInfo()} - ${this.gears} gears, ${electric}`;
  }
}

// Using Factory Pattern
const vehicles = [
  VehicleFactory.createVehicle('car', {
    brand: 'Toyota',
    model: 'Corolla',
    year: 2023,
    color: 'blue',
    doors: 4,
    fuelType: 'hybrid'
  }),

  VehicleFactory.createVehicle('motorcycle', {
    brand: 'Harley-Davidson',
    model: 'Street 750',
    color: 'black',
    engineSize: 750
  }),

  VehicleFactory.createVehicle('bicycle', {
    brand: 'Trek',
    model: 'FX 3',
    color: 'red',
    gears: 24,
    isElectric: false
  })
];

vehicles.forEach(vehicle => {
  console.log(vehicle.getDetails());
  vehicle.start();
});

Abstract Factory Pattern

// Interfaces for Abstract Factory
interface Button {
  render(): string;
  onClick(): void;
}

interface Input {
  render(): string;
  getValue(): string;
  setValue(value: string): void;
}

interface Modal {
  render(): string;
  show(): void;
  hide(): void;
}

// Abstract Factory Interface
interface UIFactory {
  createButton(text: string): Button;
  createInput(placeholder: string): Input;
  createModal(title: string): Modal;
}

// Material Design implementations
class MaterialButton implements Button {
  constructor(private text: string) {}

  render(): string {
    return `<button class="material-button">${this.text}</button>`;
  }

  onClick(): void {
    console.log(`Material button '${this.text}' clicked`);
  }
}

class MaterialInput implements Input {
  private value: string = '';

  constructor(private placeholder: string) {}

  render(): string {
    return `<input class="material-input" placeholder="${this.placeholder}" />`;
  }

  getValue(): string {
    return this.value;
  }

  setValue(value: string): void {
    this.value = value;
    console.log(`Material input value set to: ${value}`);
  }
}

class MaterialModal implements Modal {
  private isVisible: boolean = false;

  constructor(private title: string) {}

  render(): string {
    return `
      <div class="material-modal">
        <div class="material-modal-header">${this.title}</div>
        <div class="material-modal-content"></div>
      </div>
    `;
  }

  show(): void {
    this.isVisible = true;
    console.log(`Material modal '${this.title}' shown`);
  }

  hide(): void {
    this.isVisible = false;
    console.log(`Material modal '${this.title}' hidden`);
  }
}

// Bootstrap implementations
class BootstrapButton implements Button {
  constructor(private text: string) {}

  render(): string {
    return `<button class="btn btn-primary">${this.text}</button>`;
  }

  onClick(): void {
    console.log(`Bootstrap button '${this.text}' clicked`);
  }
}

class BootstrapInput implements Input {
  private value: string = '';

  constructor(private placeholder: string) {}

  render(): string {
    return `<input class="form-control" placeholder="${this.placeholder}" />`;
  }

  getValue(): string {
    return this.value;
  }

  setValue(value: string): void {
    this.value = value;
    console.log(`Bootstrap input value set to: ${value}`);
  }
}

class BootstrapModal implements Modal {
  private isVisible: boolean = false;

  constructor(private title: string) {}

  render(): string {
    return `
      <div class="modal">
        <div class="modal-dialog">
          <div class="modal-content">
            <div class="modal-header">${this.title}</div>
            <div class="modal-body"></div>
          </div>
        </div>
      </div>
    `;
  }

  show(): void {
    this.isVisible = true;
    console.log(`Bootstrap modal '${this.title}' shown`);
  }

  hide(): void {
    this.isVisible = false;
    console.log(`Bootstrap modal '${this.title}' hidden`);
  }
}

// Concrete Factories
class MaterialUIFactory implements UIFactory {
  createButton(text: string): Button {
    return new MaterialButton(text);
  }

  createInput(placeholder: string): Input {
    return new MaterialInput(placeholder);
  }

  createModal(title: string): Modal {
    return new MaterialModal(title);
  }
}

class BootstrapUIFactory implements UIFactory {
  createButton(text: string): Button {
    return new BootstrapButton(text);
  }

  createInput(placeholder: string): Input {
    return new BootstrapInput(placeholder);
  }

  createModal(title: string): Modal {
    return new BootstrapModal(title);
  }
}

// Client class using Factory
class Application {
  private factory: UIFactory;

  constructor(theme: 'material' | 'bootstrap') {
    this.factory = theme === 'material'
      ? new MaterialUIFactory()
      : new BootstrapUIFactory();
  }

  createLoginForm(): void {
    const emailInput = this.factory.createInput('Email');
    const passwordInput = this.factory.createInput('Password');
    const loginButton = this.factory.createButton('Log in');
    const modal = this.factory.createModal('Login');

    console.log('Login form:');
    console.log(emailInput.render());
    console.log(passwordInput.render());
    console.log(loginButton.render());

    // Simulating interaction
    emailInput.setValue('user@example.com');
    passwordInput.setValue('password123');
    loginButton.onClick();
    modal.show();
  }
}

// Using Abstract Factory
const materialApp = new Application('material');
materialApp.createLoginForm();

console.log('\n---\n');

const bootstrapApp = new Application('bootstrap');
bootstrapApp.createLoginForm();

Observer Pattern - Reactive programming

The Observer Pattern is a behavioral pattern that defines a one-to-many dependency between objects. When the state of one object changes, all dependent objects are automatically notified and updated.

Basic Observer Pattern implementation

// Subject class (Observable)
class Subject {
  constructor() {
    this.observers = [];
  }

  subscribe(observer) {
    if (typeof observer.update === 'function') {
      this.observers.push(observer);
      console.log('Observer has been added');
    } else {
      throw new Error('Observer must implement the update() method');
    }
  }

  unsubscribe(observer) {
    const index = this.observers.indexOf(observer);
    if (index > -1) {
      this.observers.splice(index, 1);
      console.log('Observer has been removed');
    }
  }

  notify(data) {
    console.log(`Notifying ${this.observers.length} observers`);
    this.observers.forEach(observer => {
      observer.update(data);
    });
  }
}

// Concrete Subject - Stock market monitor
class StockPrice extends Subject {
  constructor(symbol, price) {
    super();
    this.symbol = symbol;
    this.price = price;
    this.history = [{ price, timestamp: new Date() }];
  }

  setPrice(newPrice) {
    const oldPrice = this.price;
    this.price = newPrice;

    const change = newPrice - oldPrice;
    const changePercent = ((change / oldPrice) * 100).toFixed(2);

    const priceData = {
      symbol: this.symbol,
      oldPrice,
      newPrice,
      change,
      changePercent,
      timestamp: new Date()
    };

    this.history.push({
      price: newPrice,
      timestamp: priceData.timestamp
    });

    this.notify(priceData);
  }

  getPrice() {
    return this.price;
  }

  getHistory() {
    return [...this.history];
  }
}

// Observers (subscribers)
class PriceDisplay {
  constructor(name) {
    this.name = name;
  }

  update(priceData) {
    const direction = priceData.change >= 0 ? 'โ–ฒ' : 'โ–ผ';
    const changeText = priceData.change >= 0 ? '+' : '';

    console.log(`[${this.name}] ${priceData.symbol}: ${priceData.newPrice} USD ` +
               `(${changeText}${priceData.change.toFixed(2)} / ${changeText}${priceData.changePercent}%) ${direction}`);
  }
}

class PriceAlert {
  constructor(thresholdPrice, type = 'above') {
    this.thresholdPrice = thresholdPrice;
    this.type = type; // 'above' or 'below'
    this.alerted = false;
  }

  update(priceData) {
    const shouldAlert = this.type === 'above'
      ? priceData.newPrice >= this.thresholdPrice
      : priceData.newPrice <= this.thresholdPrice;

    if (shouldAlert && !this.alerted) {
      console.log(`ALERT: ${priceData.symbol} ${this.type === 'above' ? 'exceeded' : 'dropped below'} ` +
                 `${this.thresholdPrice} USD (current price: ${priceData.newPrice} USD)`);
      this.alerted = true;
    } else if (!shouldAlert) {
      this.alerted = false;
    }
  }
}

class PortfolioTracker {
  constructor(shares) {
    this.shares = shares;
    this.initialValue = null;
  }

  update(priceData) {
    const currentValue = priceData.newPrice * this.shares;

    if (this.initialValue === null) {
      this.initialValue = priceData.oldPrice * this.shares;
    }

    const profit = currentValue - this.initialValue;
    const profitPercent = ((profit / this.initialValue) * 100).toFixed(2);

    console.log(`Portfolio: ${this.shares} shares of ${priceData.symbol} = ${currentValue.toFixed(2)} USD ` +
               `(profit/loss: ${profit.toFixed(2)} USD / ${profitPercent}%)`);
  }
}

// Using Observer Pattern
const teslaStock = new StockPrice('TSLA', 250.00);

// Creating observers
const mainDisplay = new PriceDisplay('Main screen');
const mobileApp = new PriceDisplay('Mobile app');
const highPriceAlert = new PriceAlert(260, 'above');
const lowPriceAlert = new PriceAlert(240, 'below');
const myPortfolio = new PortfolioTracker(10);

// Subscribing observers
teslaStock.subscribe(mainDisplay);
teslaStock.subscribe(mobileApp);
teslaStock.subscribe(highPriceAlert);
teslaStock.subscribe(lowPriceAlert);
teslaStock.subscribe(myPortfolio);

// Simulating price changes
console.log('=== TSLA Stock Price Change Simulation ===\n');

teslaStock.setPrice(255.75);
console.log('');

teslaStock.setPrice(262.30);
console.log('');

teslaStock.setPrice(245.20);
console.log('');

teslaStock.setPrice(235.80);

Observer Pattern with Event Emitter

// TypeScript implementation with Event Emitter
interface EventListener<T = any> {
  (data: T): void;
}

class EventEmitter<T extends Record<string, any> = Record<string, any>> {
  private listeners: Map<keyof T, Set<EventListener<any>>> = new Map();

  on<K extends keyof T>(event: K, listener: EventListener<T[K]>): () => void {
    if (!this.listeners.has(event)) {
      this.listeners.set(event, new Set());
    }

    this.listeners.get(event)!.add(listener);

    // Return an unsubscribe function
    return () => this.off(event, listener);
  }

  off<K extends keyof T>(event: K, listener: EventListener<T[K]>): void {
    const eventListeners = this.listeners.get(event);
    if (eventListeners) {
      eventListeners.delete(listener);
      if (eventListeners.size === 0) {
        this.listeners.delete(event);
      }
    }
  }

  emit<K extends keyof T>(event: K, data: T[K]): void {
    const eventListeners = this.listeners.get(event);
    if (eventListeners) {
      eventListeners.forEach(listener => {
        try {
          listener(data);
        } catch (error) {
          console.error(`Error in event listener for ${String(event)}:`, error);
        }
      });
    }
  }

  once<K extends keyof T>(event: K, listener: EventListener<T[K]>): void {
    const onceListener = (data: T[K]) => {
      listener(data);
      this.off(event, onceListener);
    };

    this.on(event, onceListener);
  }

  removeAllListeners<K extends keyof T>(event?: K): void {
    if (event) {
      this.listeners.delete(event);
    } else {
      this.listeners.clear();
    }
  }

  listenerCount<K extends keyof T>(event: K): number {
    const eventListeners = this.listeners.get(event);
    return eventListeners ? eventListeners.size : 0;
  }
}

// Event type definitions
interface UserEvents {
  login: { userId: string; email: string; timestamp: Date };
  logout: { userId: string; timestamp: Date };
  profileUpdate: { userId: string; changes: Record<string, any> };
  passwordChange: { userId: string; timestamp: Date };
}

// Usage example with TypeScript
class UserService extends EventEmitter<UserEvents> {
  private users: Map<string, any> = new Map();

  login(email: string, password: string): boolean {
    // Simulating login
    const userId = 'user_' + Math.random().toString(36).slice(2, 11);

    this.users.set(userId, {
      id: userId,
      email,
      lastLogin: new Date()
    });

    this.emit('login', {
      userId,
      email,
      timestamp: new Date()
    });

    return true;
  }

  logout(userId: string): void {
    if (this.users.has(userId)) {
      this.emit('logout', {
        userId,
        timestamp: new Date()
      });

      this.users.delete(userId);
    }
  }

  updateProfile(userId: string, changes: Record<string, any>): void {
    if (this.users.has(userId)) {
      const user = this.users.get(userId);
      const updatedUser = { ...user, ...changes };
      this.users.set(userId, updatedUser);

      this.emit('profileUpdate', {
        userId,
        changes
      });
    }
  }

  changePassword(userId: string, newPassword: string): void {
    if (this.users.has(userId)) {
      // Simulating password change
      this.emit('passwordChange', {
        userId,
        timestamp: new Date()
      });
    }
  }
}

// Usage
const userService = new UserService();

// Listening for events
const unsubscribeLogin = userService.on('login', (data) => {
  console.log(`User ${data.email} logged in at ${data.timestamp.toLocaleTimeString()}`);
});

userService.on('logout', (data) => {
  console.log(`User ${data.userId} logged out at ${data.timestamp.toLocaleTimeString()}`);
});

userService.on('profileUpdate', (data) => {
  console.log(`User ${data.userId} updated their profile:`, data.changes);
});

userService.once('passwordChange', (data) => {
  console.log(`Password has been changed for user ${data.userId}`);
});

// Testing
console.log('=== Test User Service Events ===\n');

const success = userService.login('jan@example.com', 'password123');
if (success) {
  const userId = Array.from(userService['users'].keys())[0];

  setTimeout(() => {
    userService.updateProfile(userId, {
      name: 'Jan Kowalski',
      age: 30
    });
  }, 1000);

  setTimeout(() => {
    userService.changePassword(userId, 'newPassword456');
  }, 2000);

  setTimeout(() => {
    userService.logout(userId);
  }, 3000);
}

Comparing patterns and best practices

When to use which pattern?

  1. Module Pattern / Revealing Module Pattern:

    • Use it when you need encapsulation and privacy
    • Use it for creating singletons
    • Use it for organizing code into namespaces
    • Avoid it when you need multiple instances
    • Avoid it when you need inheritance
  2. Factory Pattern:

    • Use it when the object type is determined at runtime
    • Use it for unifying the object creation process
    • Use it when you have many similar classes
    • Avoid it when you have only one class to create
    • Avoid it for simple objects
  3. Observer Pattern:

    • Use it for reactive programming
    • Use it when changes in one object affect many others
    • Use it for implementing event-driven architecture
    • Avoid it when you have simple, direct relationships
    • Avoid it when the sender waits for a result from the receiver: a plain method call is enough then

Combining patterns in practice

Finally, an example in which three patterns work together: the Module Pattern hides the state, a static method creates the notifications, and the Observer sends them to subscribers.

// Example of combining patterns in a practical application
interface NotificationData {
  message: string;
  type: 'info' | 'warning' | 'error' | 'success';
  timestamp: Date;
}

// Singleton with Module Pattern + Observer Pattern
const NotificationSystem = (function() {
  // Private variables
  let instance: NotificationSystem | null = null;
  let notifications: NotificationData[] = [];
  let observers: Array<(notification: NotificationData) => void> = [];

  class NotificationSystem {
    // Static factory method (a simple factory, not the Factory Method pattern)
    static createNotification(message: string, type: NotificationData['type']): NotificationData {
      return {
        message,
        type,
        timestamp: new Date()
      };
    }

    addNotification(message: string, type: NotificationData['type']): void {
      const notification = NotificationSystem.createNotification(message, type);
      notifications.push(notification);
      this.notifyObservers(notification);
    }

    // Observer Pattern methods
    subscribe(callback: (notification: NotificationData) => void): () => void {
      observers.push(callback);

      return () => {
        const index = observers.indexOf(callback);
        if (index > -1) {
          observers.splice(index, 1);
        }
      };
    }

    private notifyObservers(notification: NotificationData): void {
      observers.forEach(observer => observer(notification));
    }

    getNotifications(): NotificationData[] {
      return [...notifications];
    }

    clearNotifications(): void {
      notifications = [];
    }
  }

  // Singleton implementation
  return {
    getInstance(): NotificationSystem {
      if (!instance) {
        instance = new NotificationSystem();
      }
      return instance;
    }
  };
})();

// Using combined patterns
const notificationService = NotificationSystem.getInstance();

// Subscribers (Observer Pattern)
const unsubscribe1 = notificationService.subscribe((notification) => {
  console.log(`[UI] ${notification.type.toUpperCase()}: ${notification.message}`);
});

const unsubscribe2 = notificationService.subscribe((notification) => {
  if (notification.type === 'error') {
    console.log(`[LOG] Error logged: ${notification.message} at ${notification.timestamp}`);
  }
});

// Testing
notificationService.addNotification('Welcome to the application!', 'info');
notificationService.addNotification('Warning: Low disk space', 'warning');
notificationService.addNotification('Server connection error', 'error');
notificationService.addNotification('Data saved successfully', 'success');

Summary

The Module, Factory, and Observer design patterns are the foundations of modern JavaScript/TypeScript programming:

  • Module Pattern provides encapsulation and code organization
  • Revealing Module Pattern improves readability through clear public API definition
  • Factory Pattern abstracts the object creation process
  • Observer Pattern enables reactive programming and loose coupling

Just as ancient builders used proven architectural patterns, modern programmers use these design patterns to create solid, scalable applications. Knowledge of these patterns is essential for every JavaScript/TypeScript programmer.

Code for this lesson: index.js
// Module pattern - Park management system
// Exercise: Implement the ParkCore class with a module system

class ParkCore {
  constructor(name) {
    this.name = name;
    this.modules = new Map();
    this.isRunning = false;
  }

  // Implement the methods:
  // registerModule(name, module) - registers a module
  // getModule(name) - returns a module
  // start() - starts all modules

  registerModule(name, module) {
    // Your code here
  }

  getModule(name) {
    // Your code here
  }

  start() {
    // Your code here
  }
}

const park = new ParkCore("Jurassic Park");
console.log("Park:", park.name);

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. Which design pattern is best for ensuring that only one instance of the security system exists?

  1. QuestionQuiz: System Architecture

Useful articles