Cours JavaScript et TypeScript · Module 9: Design patterns et architecture

Patterns de conception en JavaScript/TypeScript - Module, Factory et Observer

21 min de lecture ·
Dans cette leçon6

NOTE : Matériel approfondi - Plan d'étude

Ce module contient un matériel pédagogique très dense. Tu n'as pas besoin de tout assimiler d'un coup ! Voici un ordre d'apprentissage suggéré :

Étape 1 - Fondamentaux (priorité : haute)

  • Module Pattern et Revealing Module Pattern
  • Factory Pattern
  • Observer Pattern
  • Singleton Pattern

Étape 2 - Architecture (priorité : moyenne)

  • Les principes SOLID
  • Dependency Injection et Event Bus

Étape 3 - Programmation fonctionnelle et état (priorité : moyenne)

  • Fonctions pures, immutabilité, currying et composition
  • Patterns de gestion d'état : Flux, Event Sourcing, machines à états

Étape 4 - Performance et pratique (à étudier selon les besoins)

  • Code splitting, tree shaking et lazy loading
  • Optimisation du bundle
  • Architecture événementielle et projet final

Conseils :

  • Assimile le matériel de façon séquentielle, section par section
  • Après chaque pattern, fais une pause et exerce-toi par toi-même
  • Reviens aux sujets plus difficiles après un certain temps
  • Ne saute pas les fondamentaux - ils sont la clé pour comprendre le reste
  • Les patterns avancés peuvent être étudiés au besoin dans tes projets

Souviens-toi : il vaut mieux bien comprendre les bases que survoler tout superficiellement !


Tout comme les architectes de l'Antiquité utilisaient des schémas de construction éprouvés pour bâtir des temples durables, les développeurs modernes utilisent des patterns de conception pour créer un code solide et évolutif. Dans cette leçon, tu vas découvrir quatre patterns fondamentaux : Module Pattern, Revealing Module Pattern, Factory Pattern et Observer Pattern, qui constituent la base de nombreuses applications JavaScript et TypeScript modernes.

Module Pattern - Encapsulation et confidentialité

Le Module Pattern est l'un des patterns les plus importants en JavaScript : il permet d'encapsuler du code et de créer des variables et méthodes privées. Avant l'arrivée des modules ES6, c'était le principal moyen d'organiser le code en modules.

Implémentation classique du Module Pattern

// 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 avec paramètres

// 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 - Encapsulation améliorée

Le Revealing Module Pattern est une évolution du Module Pattern qui offre une meilleure lisibilité et une meilleure séparation entre fonctions privées et publiques.

Implémentation de base du Revealing Module Pattern

// 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 - exposition des méthodes publiques
  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 avec le 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 - exposition des méthodes publiques
  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 - Création d'objets

Le Factory Pattern est un pattern de création qui permet de créer des objets sans préciser la classe concrète de l'objet à instancier. Il est particulièrement utile lorsqu'on a différents types d'objets ayant une structure similaire.

Factory Pattern simple

// 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 - Programmation réactive

L'Observer Pattern est un pattern comportemental qui définit une dépendance un-à-plusieurs entre objets. Lorsque l'état d'un objet change, tous les objets qui en dépendent sont automatiquement notifiés et mis à jour.

Implémentation de base de l'Observer Pattern

// 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 avec un 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);
}

Comparaison des patterns et bonnes pratiques

Quand utiliser quel pattern ?

  1. Module Pattern / Revealing Module Pattern :

    • À utiliser quand tu as besoin d'encapsulation et de confidentialité
    • À utiliser pour créer des singletons
    • À utiliser pour organiser le code en espaces de noms
    • À éviter quand tu as besoin de plusieurs instances
    • À éviter quand tu as besoin d'héritage
  2. Factory Pattern :

    • À utiliser quand le type d'objet est déterminé à l'exécution
    • À utiliser pour unifier le processus de création d'objets
    • À utiliser quand tu as de nombreuses classes similaires
    • À éviter quand tu n'as qu'une seule classe à créer
    • À éviter pour des objets simples
  3. Observer Pattern :

    • À utiliser pour la programmation réactive
    • À utiliser quand les changements d'un objet affectent plusieurs autres
    • À utiliser pour mettre en place une architecture événementielle
    • À éviter quand les relations sont simples et directes
    • À éviter quand l'émetteur attend un résultat du destinataire : un simple appel de méthode suffit alors

Combiner les patterns en pratique

Pour finir, un exemple où trois patterns travaillent ensemble : le Module Pattern cache l'état, une méthode statique crée les notifications et l'Observer les envoie aux abonnés.

// 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');

Résumé

Les patterns Module, Factory et Observer sont les fondations de la programmation moderne en JavaScript/TypeScript :

  • Module Pattern assure l'encapsulation et l'organisation du code
  • Revealing Module Pattern améliore la lisibilité grâce à une définition claire de l'API publique
  • Factory Pattern abstrait le processus de création d'objets
  • Observer Pattern permet la programmation réactive et un couplage faible

Tout comme les bâtisseurs de l'Antiquité utilisaient des schémas architecturaux éprouvés, les développeurs modernes utilisent ces patterns de conception pour créer des applications solides et évolutives. La maîtrise de ces patterns est essentielle pour tout développeur JavaScript/TypeScript.

Code de cette leçon : index.js
// Pattern Module - système de gestion du parc
// Exercice : implémente la classe ParkCore avec un système de modules

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

  // Implémente les méthodes :
  // registerModule(name, module) - enregistre un module
  // getModule(name) - retourne un module
  // start() - démarre tous les modules

  registerModule(name, module) {
    // Ton code ici
  }

  getModule(name) {
    // Ton code ici
  }

  start() {
    // Ton code ici
  }
}

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

Entrées de la documentation utilisées dans cette leçon

Tu as repéré une erreur dans cette leçon ?

Teste tes connaissances

Réponds aux questions de cette leçon. Choisis une réponse pour voir tout de suite si elle est correcte.

  1. 1. Quel pattern de conception est le mieux adapté pour garantir qu'une seule instance du système de sécurité existe ?

  1. QuestionQuiz : architecture du système

Articles utiles