[typescript] 브릿지 패턴과 타입스크립트의 결합 사례

브릿지 패턴은 객체의 구현을 해당 구현으로부터 분리시키고, 추상화 계층과 구현 계층 간의 연결을 제공하여 두 계층이 독립적으로 변형될 수 있도록 하는 디자인 패턴입니다. 타입스크립트를 사용하면 브릿지 패턴을 더 쉽게 구현하고 유지할 수 있습니다.

브릿지 패턴이란 무엇인가?

브릿지 패턴은 소프트웨어 공학에서 객체지향 디자인 패턴 중 하나로, 추상화 계층(abstraction)과 구현 계층(implementation)을 분리하여 확장성과 유연성을 높이는 패턴입니다.

타입스크립트와 브릿지 패턴

// Implementor interface
interface DrawingAPI {
  drawCircle(x: number, y: number, radius: number): void;
}

// Concrete Implementor
class DrawingAPI1 implements DrawingAPI {
  drawCircle(x: number, y: number, radius: number): void {
    console.log(`API1.circle at ${x}:${y} radius ${radius}`);
  }
}

class DrawingAPI2 implements DrawingAPI {
  drawCircle(x: number, y: number, radius: number): void {
    console.log(`API2.circle at ${x}:${y} radius ${radius}`);
  }
}

// Abstraction
abstract class Shape {
  protected drawingAPI: DrawingAPI;

  protected constructor(drawingAPI: DrawingAPI) {
    this.drawingAPI = drawingAPI;
  }

  abstract draw(): void;
}

// Refined Abstraction
class Circle extends Shape {
  private x: number;
  private y: number;
  private radius: number;

  constructor(x: number, y: number, radius: number, drawingAPI: DrawingAPI) {
    super(drawingAPI);
    this.x = x;
    this.y = y;
    this.radius = radius;
  }

  draw(): void {
    this.drawingAPI.drawCircle(this.x, this.y, this.radius);
  }
}

// Client
const circle1 = new Circle(1, 2, 3, new DrawingAPI1());
const circle2 = new Circle(5, 7, 11, new DrawingAPI2());

circle1.draw();
circle2.draw();

위 예제는 타입스크립트를 사용하여 브릿지 패턴을 구현한 것입니다. DrawingAPI는 drawCircle 메서드를 정의하는데, 이는 구현(implementation) 계층을 추상화(abstraction)한 것으로 볼 수 있습니다. 이후 DrawingAPI1과 DrawingAPI2는 실제로 구현된 구상 구현(concrete implementation) 클래스이며, Shape는 추상화 계층을 나타내며 이를 상속받는 Circle에서 draw 메서드를 구체적으로 구현합니다.

결론

타입스크립트를 사용하면 브릿지 패턴을 더 쉽게 이해하고 구현할 수 있습니다. 각 요소의 타입과 관련 메서드의 사용 여부를 명확히 정의함으로써 코드의 가독성과 유지보수성이 향상됩니다.

참고 자료