추상부와 구현부 2개의 계층으로 분리한 패턴이다.
추상부와 구현부의 연결 관계를 브릿지 라고 할수있다.
추상화와 구현부가 분리되어 있어 클라이언트코드에서 특정 구현부에 직접 의존하지 않고 추상클래스를 통해 작업을 수행한다.
이렇게 분리된 계층구조를 통해서 독립적으로 동작하고 관리하는게 브릿지패턴의 핵심
/**
* 추상화는 두 클래스의 "제어" 부분에 대한 인터페이스를 정의
* 계층. 구현의 개체에 대한 참조를 유지
* 계층화 및 모든 실제 작업을 이 개체에 위임
*/
class Abstraction {
// 추상부
protected implementation: Implementation;
constructor(implementation: Implementation) {
this.implementation = implementation;
}
operation() {
// callMeByYourName 추상메소드 생성
const result = this.implementation.operationImplementation();
return `Abstraction: Base operation with:\n${result}`;
}
}
/**
* 구현부 클래스들의 수정없이 추상부클래스를 확장할수 있다.
*/
class ExtendedAbstraction extends Abstraction {
operation(): string {
const result = this.implementation.operationImplementation();
return `ExtendedAbstraction: Extended operation with:\n${result}`;
}
}
/**
* 구현은 모든 구현 클래스에 대한 인터페이스를 정의
* 추상화의 인터페이스와 일치할 필요는 없음
* 두 인터페이스는 완전히 다를 수 있음
* 일반적으로 구현 인터페이스는 원시적인 작업만 제공하고
* 추상화 인터페이스는 이러한 원시적인 작업을 기반으로 더 높은 수준의 작업을 정의
*/
interface Implementation {
operationImplementation(): string;
}
class ConcreteImplementationA implements Implementation {
// 구현부
operationImplementation(): string {
return "ConcreteImplementationA: Here's the result on the platform A.";
}
}
class ConcreteImplementationB implements Implementation {
// 구현부
operationImplementation(): string {
return "ConcreteImplementationB: Here's the result on the platform B.";
}
}
const clientCode = (abstraction: Abstraction) => {
console.log(abstraction.operation()); // 추상부 클래스를 통해 작업을 수행
};
let implementation = new ConcreteImplementationA(); // 구현부 클래스 인스턴스
let abstraction = new Abstraction(implementation); // 추상부 클래스에 구현부 클래스를 넘겨서 추상부객체 생성
clientCode(abstraction); // 클라이언트 코드에 추상클래스를 넘김
console.log("");
implementation = new ConcreteImplementationB();
abstraction = new ExtendedAbstraction(implementation);
clientCode(abstraction);
// 출력
Abstraction: Base operation with:
ConcreteImplementationA: Here's the result on the platform A.
ExtendedAbstraction: Extended operation with:
ConcreteImplementationB: Here's the result on the platform B.
장점
- 느슨한 결합도 / 추상부 코드를 이용해 구현체 코드에 영향을 안줌
- 추상부/구현부를 독립적으로 관리하기에 동작과 확장에 좋음
단점
- 객체를 세분화 할수록 계층 구조의 복잡도가 증가 / 관리해야하는 포인트 증가
분리가 많아지니 관리해야하는 파일의 수가 많아질수 있음 [1개파일에 적은코드로 여러파일관리 vs 1개파일에 많은코드로 적은파일관리] 관점차이도 존재할듯
vs 어댑터패턴 (Adapter Pattern)
- 브릿지 패턴은 구조화하면서 사전에 설계한다
- 어댑터 패턴은 이미 만들어진 구조에서 추가나 호환이 필요한 경우 인터페이스를 만들어서 추가한다.
참고
https://refactoring.guru/ko/design-patterns/bridge/typescript/example#
타입스크립트로 작성된 브리지 / 디자인 패턴들
refactoring.guru
'디자인패턴GoF > 구조패턴' 카테고리의 다른 글
| 자바스크립트로 이해해보는 어댑터패턴 (Adapter Pattern) In 구조패턴 (1) | 2024.01.21 |
|---|