#15StructuralMedium

Mixin Pattern

Mixin Pattern

공통 기능을 별도 객체에 모아두고, 여러 클래스에 합성할 수 있는 mixin 헬퍼를 만드세요.

API

export function applyMixins<T>(
  target: { prototype: T },
  ...mixins: object[]
): void;

동작

  • 각 mixin 객체의 **자기 소유 프로퍼티(메서드)**를 target.prototype에 복사
  • 같은 이름이 여러 mixin에 있으면 마지막 mixin이 우선 (덮어씀)
  • target에 이미 있는 메서드는 mixin이 덮어쓰지 않음
  • prototype chain에서 상속받은 프로퍼티는 복사 대상이 아님 (own only)

사용 예시

class Robot {}
const Walker = { walk() { return 'walking'; } };
const Talker = { talk() { return 'hi'; } };
import { applyMixins } from './solution';
applyMixins(Robot, Walker, Talker);
const r = new Robot() as Robot & { walk(): string; talk(): string };
r.walk();  // 'walking'
r.talk();  // 'hi'

학습 포인트

  • 다중 상속이 없는 JS에서 "기능 합성" 흉내내기
  • Object.getOwnPropertyNames + Object.defineProperty로 prototype에 직접 부착
  • 클래스 계층을 깊게 만드는 대신 작은 조각을 합성