객체 구축하기
Coddy JavaScript 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨 — 56개 중 49번째.
깊은 상속과 "has-a" 관계의 문제점을 이제 이해했으므로, 작고 재사용 가능한 컴포넌트들을 결합하여 객체를 만드는 방법을 배워봅시다. 이 접근 방식은 우리에게 최대한의 유연성을 제공합니다!
기본 패턴:
// 1단계: 작고 집중된 컴포넌트 만들기
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`);
}
}// 2단계: 컴포넌트를 결합하여 객체 구축
class Car {
constructor(brand, enginePower, wheelCount) {
this.brand = brand;
this.engine = new Engine(enginePower); // 엔진을 가지고 있음 (HAS-A 관계)
this.wheels = new Wheels(wheelCount); // 바퀴를 가지고 있음 (HAS-A 관계)
}
drive() {
console.log(`${this.brand} is driving:`);
this.engine.start();
this.wheels.rotate();
}
}// 3단계: 구성된 객체 사용
const myCar = new Car('Toyota', 150, 4);
myCar.drive();
// 출력:
// Toyota가 주행 중입니다:
// 엔진(150HP) 시동 중...
// 4개의 바퀴가 회전 중진정한 힘: 컴포넌트 조합하기:
// 더 전문화된 컴포넌트들
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`);
}
}// 다양한 조합으로 서로 다른 자동차 제작
class SportsCar {
constructor(brand) {
this.brand = brand;
this.engine = new Engine(300);
this.wheels = new Wheels(4);
this.turbo = new TurboCharger(); // 스포츠카에는 터보가 장착됨
this.soundSystem = new SoundSystem('Premium'); // 그리고 좋은 사운드 시스템
}
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);
// 경제형 자동차에는 터보가 없습니다
this.soundSystem = new SoundSystem('Basic'); // 기본 사운드만 제공
}
drive() {
console.log(`${this.brand} driving efficiently:`);
this.engine.start();
this.wheels.rotate();
this.soundSystem.playMusic();
}
}// 이것이 얼마나 유연한지 보세요!
const ferrari = new SportsCar('Ferrari');
const honda = new EconomyCar('Honda');
ferrari.raceMode(); // 터보 부스트 기능이 있습니다!
ferrari.cruise(); // 프리미엄 사운드 기능이 있습니다!
honda.drive(); // 기본적인 기능만 있습니다이 접근 방식은 복잡한 상속 체인 없이도 동작을 자유롭게 조합할 수 있는 유연성을 제공합니다!
챌린지
SmartBulb.js 파일에 있는 SmartBulb 메서드들을 완성하세요.
- 전등을 켜기 위해
activate()메서드를 구현하세요. - 밝기를 설정하고 정확히
Brightness set to ${this.brightness.level}%라고 로그를 남기도록adjustBrightness()메서드를 구현하세요.
치트 시트
객체는 깊은 상속을 사용하는 대신 작고 재사용 가능한 컴포넌트들을 결합하여 구축할 수 있습니다. 이를 합성(composition)이라고 하며 "has-a" 관계를 따릅니다.
기본 합성 패턴:
// 1단계: 작고 집중된 컴포넌트 생성
class Engine {
constructor(power) {
this.power = power;
}
start() {
console.log(`Engine (${this.power}HP) starting...`);
}
}
// 2단계: 컴포넌트들을 결합하여 객체 구축
class Car {
constructor(brand, enginePower) {
this.brand = brand;
this.engine = new Engine(enginePower); // 엔진을 가지고 있음(HAS-A)
}
drive() {
this.engine.start();
}
}유연성을 위한 컴포넌트 조합:
class TurboCharger {
boost() {
console.log('Turbo engaged!');
}
}
class SportsCar {
constructor(brand) {
this.brand = brand;
this.engine = new Engine(300);
this.turbo = new TurboCharger(); // 터보 컴포넌트 추가
}
raceMode() {
this.engine.start();
this.turbo.boost();
}
}
class EconomyCar {
constructor(brand) {
this.brand = brand;
this.engine = new Engine(100);
// 터보 컴포넌트 없음
}
}합성을 사용하면 복잡한 상속 체인 없이도 다양한 기능 조합을 가진 객체를 구축할 수 있습니다.
직접 해보기
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);
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.