[TYPESCRIPT] 타입스크립트 디자인 패턴 - Adapter

Adapter Pattern

The adapter pattern is one of the structural software design patterns.

Structural: 객체간의 관계를 처리

이점

  1. 클라이언트 인터페이스를 변경하지 않고 새로운 시스템의 기능을 제공하게 한다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// adapter.ts
import { IGeoCoder, GeoCoder } from './impl-class';
import { Locator } from './new-class';

export class GeocodingAdapter implements IGeoCoder {
private latitude: number;
private longitude: number;
private type: string;
constructor(latitude, longitude, type) {
this.latitude = latitude;
this.longitude = longitude;
this.type = type;
}

locate(): string {
if (this.type === 'GeoCoder') {
const geocoder = new GeoCoder(this.latitude, this.longitude);
return geocoder.locate();

} else if (this.type === 'Locator') {
const locator = new Locator(this.latitude, this.longitude);
return locator.geocode();
} else {
throw new Error('Please use either GeoCoder or Locator');
}
}
}
1
2
3
4
5
6
7
8
9
10
// client.ts
import { GeocodingAdapter } from './adapter';

const gAdapter = new GeocodingAdapter(51.5074, 0.1278, 'Locator');
const gAdapter2 = new GeocodingAdapter(51.5074, 0.1278, 'GeoCoder');
const locationFromLocator = gAdapter.locate();
const locationFromGeoCoder = gAdapter2.locate();

console.log(locationFromLocator);
console.log(locationFromGeoCoder);