Menu
Coddy logo textTech

Construction d'objets

Fait partie de la section Programmation Orientée Objet du Journey JavaScript de Coddy — leçon 49 sur 56.

Maintenant que nous comprenons les problèmes liés à l'héritage profond et à la relation « a un » (has-a), apprenons comment construire des objets en combinant de petits composants réutilisables. Cette approche nous offre une flexibilité maximale ! 

Le modèle de base :

// Étape 1 : Créer de petits composants ciblés
class Engine {
  constructor(power) {
    this.power = power;
  }
  
  start() {
    console.log(`Engine (${this.power}HP) starting...`);
  }
}

class Wheels {
  constructor(count) {
    this.count = count;
  }
  
  rotate() {
    console.log(`${this.count} wheels rotating`);
  }
}
// Étape 2 : Construire des objets en combinant des composants
class Car {
  constructor(brand, enginePower, wheelCount) {
    this.brand = brand;
    this.engine = new Engine(enginePower);    // POSSÈDE UN moteur
    this.wheels = new Wheels(wheelCount);     // POSSÈDE des roues
  }
  
  drive() {
    console.log(`${this.brand} is driving:`);
    this.engine.start();
    this.wheels.rotate();
  }
}
// Étape 3 : Utiliser l'objet composé
const myCar = new Car('Toyota', 150, 4);
myCar.drive();
// Sortie :
// Toyota conduit :
// Démarrage du moteur (150HP)...
// 4 roues en rotation

La véritable puissance : Mélanger et assortir les composants :

// Composants plus spécialisés
class TurboCharger {
  boost() {
    console.log('Turbo engaged! Extra power!');
  }
}

class SoundSystem {
  constructor(type) {
    this.type = type;
  }
  
  playMusic() {
    console.log(`Playing music on ${this.type} sound system`);
  }
}
// Construire différentes voitures avec différentes combinaisons
class SportsCar {
  constructor(brand) {
    this.brand = brand;
    this.engine = new Engine(300);
    this.wheels = new Wheels(4);
    this.turbo = new TurboCharger();      // La voiture de sport reçoit un turbo
    this.soundSystem = new SoundSystem('Premium'); // Et un bon système audio
  }
  
  raceMode() {
    console.log(`${this.brand} in race mode:`);
    this.engine.start();
    this.turbo.boost();
    this.wheels.rotate();
    console.log('VROOOOM!');
  }
  
  cruise() {
    console.log(`${this.brand} cruising:`);
    this.engine.start();
    this.wheels.rotate();
    this.soundSystem.playMusic();
  }
}
class EconomyCar {
  constructor(brand) {
    this.brand = brand;
    this.engine = new Engine(100);
    this.wheels = new Wheels(4);
    // Pas de turbo pour une voiture économique
    this.soundSystem = new SoundSystem('Basic'); // Son de base uniquement
  }
  
  drive() {
    console.log(`${this.brand} driving efficiently:`);
    this.engine.start();
    this.wheels.rotate();
    this.soundSystem.playMusic();
  }
}
// Voyez à quel point c'est flexible !
const ferrari = new SportsCar('Ferrari');
const honda = new EconomyCar('Honda');

ferrari.raceMode();  // Possède un turbo boost !
ferrari.cruise();    // Possède un son premium !

honda.drive();       // Juste des fonctionnalités de base

Cette approche vous offre la flexibilité de combiner et d'assortir les comportements sans chaînes d'héritage complexes !

challenge icon

Défi

Complétez les méthodes de SmartBulb dans le fichier SmartBulb.js.

  1. Implémentez la méthode activate() pour allumer la lumière.
  2. Implémentez la méthode adjustBrightness() pour régler la luminosité et enregistrez exactement : Brightness set to ${this.brightness.level}%

Essayez vous-même

import { SmartBulb } from './SmartBulb.js';

const bedroomLight = new SmartBulb('warm white');

console.log('1. Activating light:');
bedroomLight.activate();

console.log('\n2. Adjusting brightness:');
bedroomLight.adjustBrightness(75);
quiz iconTestez-vous

Cette leçon comprend un petit quiz. Commencez la leçon pour y répondre et suivre votre progression.

Toutes les leçons de Programmation Orientée Objet