Menu
Coddy logo textTech

Construindo objetos

Parte da seção Programação Orientada a Objetos do Journey de JavaScript da Coddy — lição 49 de 56.

Agora que entendemos os problemas com a herança profunda e o relacionamento "has-a", vamos aprender como construir objetos combinando componentes pequenos e reutilizáveis. Esta abordagem nos dá flexibilidade máxima! 

O Padrão Básico:

// Passo 1: Crie componentes pequenos e focados
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`);
  }
}
// Passo 2: Construir objetos combinando componentes
class Car {
  constructor(brand, enginePower, wheelCount) {
    this.brand = brand;
    this.engine = new Engine(enginePower);    // TEM UM motor
    this.wheels = new Wheels(wheelCount);     // TEM rodas
  }
  
  drive() {
    console.log(`${this.brand} is driving:`);
    this.engine.start();
    this.wheels.rotate();
  }
}
// Passo 3: Use o objeto composto
const myCar = new Car('Toyota', 150, 4);
myCar.drive();
// Saída:
// Toyota is driving:
// Engine (150HP) starting...
// 4 wheels rotating

O Verdadeiro Poder: Misturar e Combinar Componentes:

// Componentes mais especializados
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`);
  }
}
// Construa carros diferentes com combinações diferentes
class SportsCar {
  constructor(brand) {
    this.brand = brand;
    this.engine = new Engine(300);
    this.wheels = new Wheels(4);
    this.turbo = new TurboCharger();      // Carro esportivo ganha turbo
    this.soundSystem = new SoundSystem('Premium'); // E som de qualidade
  }
  
  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);
    // Sem turbo para carro econômico
    this.soundSystem = new SoundSystem('Basic'); // Apenas som básico
  }
  
  drive() {
    console.log(`${this.brand} driving efficiently:`);
    this.engine.start();
    this.wheels.rotate();
    this.soundSystem.playMusic();
  }
}
// Veja como isso é flexível!
const ferrari = new SportsCar('Ferrari');
const honda = new EconomyCar('Honda');

ferrari.raceMode();  // Tem turbo boost!
ferrari.cruise();    // Tem som premium!

honda.drive();       // Apenas recursos básicos

Esta abordagem oferece flexibilidade para combinar comportamentos sem cadeias de herança complexas!

challenge icon

Desafio

Complete os métodos da SmartBulb no arquivo SmartBulb.js.

  1. Implemente o método activate() para ligar a luz.
  2. Implemente o método adjustBrightness() para definir o brilho e registrar exatamente: Brightness set to ${this.brightness.level}%

Folha de consulta

Objetos podem ser construídos combinando componentes pequenos e reutilizáveis em vez de usar herança profunda. Isso é chamado de composição e segue o relacionamento "tem-um" (has-a).

Padrão básico de composição:

// Passo 1: Criar componentes pequenos e focados
class Engine {
  constructor(power) {
    this.power = power;
  }
  
  start() {
    console.log(`Engine (${this.power}HP) starting...`);
  }
}

// Passo 2: Construir objetos combinando componentes
class Car {
  constructor(brand, enginePower) {
    this.brand = brand;
    this.engine = new Engine(enginePower);  // TEM-UM motor
  }
  
  drive() {
    this.engine.start();
  }
}

Misture e combine componentes para flexibilidade:

class TurboCharger {
  boost() {
    console.log('Turbo engaged!');
  }
}

class SportsCar {
  constructor(brand) {
    this.brand = brand;
    this.engine = new Engine(300);
    this.turbo = new TurboCharger();  // Adiciona componente turbo
  }
  
  raceMode() {
    this.engine.start();
    this.turbo.boost();
  }
}

class EconomyCar {
  constructor(brand) {
    this.brand = brand;
    this.engine = new Engine(100);
    // Sem componente turbo
  }
}

A composição permite construir objetos com diferentes combinações de recursos sem cadeias de herança complexas.

Experimente você mesmo

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 iconTeste seus conhecimentos

Esta lição inclui um quiz rápido. Comece a lição para respondê-lo e acompanhar seu progresso.

Todas as lições de Programação Orientada a Objetos