#22StructuralMedium

믹스인 패턴 (Serializable + Loggable)

믹스인 패턴

믹스인 패턴을 사용해 상속 없이 여러 클래스에 재사용 가능한 기능을 주입하세요.

SerializabletoJSON()을, Loggablelog()를 제공합니다. 두 믹스인을 User 클래스에 적용해 두 메서드를 모두 사용할 수 있게 만드세요.

API

export function applyMixins(target: any, ...mixins: any[]): void;

export const Serializable = {
  toJSON(this: any): string { return JSON.stringify(this); }
};
export const Loggable = {
  log(this: any): string { return `[LOG] ${this.name}`; }
};

export class User { constructor(public name: string) {} }
applyMixins(User, [Serializable, Loggable]);

예시

const u = new User('Alice') as User & { toJSON(): string; log(): string };
u.toJSON(); // '{"name":"Alice"}'
u.log();    // '[LOG] Alice'

학습 포인트

  • 상속 없이 prototype에 메서드 복사 (TS/JS)
  • 디폴트 메서드 인터페이스 (Java/Kotlin)
  • 다중 상속/조합 (C++)
  • this 바인딩으로 인스턴스 상태 접근
언어: