장 실습: 카페 주문에 결제 더하기
4장에서 만든 주문·할인 클래스와 로거 인터페이스를 결제 처리기에 연결하고, 정상 주문과 빈 주문의 금액·기록을 확인합니다.
인터페이스를 활용한 설계에서는 처리 클래스가 기록 방법을 직접 고르지 않도록 바꾸었습니다. 이번에는 그 구조를 앞에서 만든 카페 주문에 붙여, 할인 방법과 기록 방법을 바꾸어 끼울 수 있는 결제를 완성합니다.
이 실습을 마치면 다음을 할 수 있습니다.
- 주문·할인·기록 객체를 생성자로 연결합니다.
- 정상 주문과 빈 주문이 남기는 금액과 기록을 대조합니다.
시작 상태
개발 환경 설정의 ts-first 프로젝트를 씁니다. 클래스 기본 문법부터 추상 클래스까지의 연습에서 만든 shop.ts가 있고, MenuItem, Order, SetMenu, Discount와 두 할인 클래스가 들어 있는 상태입니다. 앞 글의 design.ts는 로거 구현을 참고할 때 엽니다. tsconfig.json의 include를 ["shop.ts"]로 바꿉니다.
기존 프로젝트가 없다면 개발 환경 설정의 설치 과정을 먼저 마칩니다. 아래 완성 파일에서 interface Logger 앞까지 옮기면 같은 시작 상태를 만들 수 있습니다. 각 단계 뒤에는 ts-first에서 다음 명령으로 확인합니다.
tsc -p .
node dist/shop.js1단계: 결제할 주문 확인하기
order에는 아메리카노 두 잔, 가격을 5200원으로 바꾼 라떼 한 잔, 8000원인 점심 세트 하나가 들어 있습니다. 수량이 0인 추가는 거절됩니다. 가격과 수량을 손으로 계산해 order.total이 22200원인지 확인합니다.
체크포인트: Order에는 label()이 있고, 주문의 설명은 주문 3건, 합계 22200원입니다. 여기서 세 건은 음료의 총수량이 아니라 add()로 담긴 세 줄입니다.
2단계: 할인과 기록을 넘겨 결제하기
- 앞 글의
Logger와MemoryLogger를shop.ts에 옮겨 적습니다. Checkout은Discount와Logger를 생성자로 받고, 구체적인 할인 클래스나 로거 클래스의 이름을 쓰지 않습니다.pay(target)은 주문을 받아 결제할 금액을 돌려줍니다. 합계가 0이면 로거에빈 주문은 결제하지 않습니다.를 경고로 남기고 0을 돌려줍니다. 그렇지 않으면결제 시작: 주문 3건, 합계 22200원과결제 금액: 19980원의 모양으로 기록을 두 번 남깁니다.- 10% 할인과
MemoryLogger로Checkout을 만들어, 지금까지의order와 빈 주문을 차례로 결제하고, 두 결과와 로거의 기록을 출력합니다.
힌트: 주문의 설명은 Order의 label()이, 할인한 금액은 Discount의 apply가 돌려줍니다.
체크포인트: Checkout 안에서는 Discount와 Logger만 사용합니다. 10% 할인을 넣은 정상 주문의 결제액은 19980원이고, 빈 주문은 0원입니다. 두 경우에 어떤 기록을 남길지 먼저 적어 보세요.
3단계: 금액과 기록 대조하기
tsc -p .이 진단 없이 끝나고, node dist/shop.js가 앞 글까지의 열다섯 줄 아래에 다음 네 줄을 출력하면 완성입니다.
10% 쿠폰: 2220원 할인
19980
0
INFO: 결제 시작: 주문 3건, 합계 22200원 | INFO: 결제 금액: 19980원 | WARN: 빈 주문은 결제하지 않습니다.첫 줄은 Discount의 apply가 찍은 안내이고, 둘째와 셋째 줄이 두 번의 pay가 돌려준 금액입니다. 빈 주문은 total이 0이어서 경고만 남겼습니다. Checkout은 구체적인 클래스를 모르므로 new Checkout(new FixedDiscount(3000), shopLogger)처럼 만드는 줄만 바꾸어 다른 할인을 끼울 수 있습니다.
다를 때 먼저 볼 곳
| 증상 | 먼저 볼 곳 |
|---|---|
| 이름이 겹친다는 진단이 여러 개 나온다 | include가 ["shop.ts"] 하나인지. design.ts가 함께 있으면 MemoryLogger가 겹칩니다 |
Checkout에서 label이 없다는 TS2339가 나온다 | 상속과 구현의 3번에서 Order에 label()을 더했는지 |
| 합계가 22200이 아니다 | latte.price = 5200과 order.add(lunchSet, 1)이 결제보다 위에 있는지 |
완성 파일
shop.ts 전체 보기
class MenuItem {
static count = 0;
name: string;
private _price: number;
constructor(name: string, price: number) {
if (!MenuItem.isValidPrice(price)) {
throw new Error("가격은 0 이상의 정수여야 합니다.");
}
this.name = name;
this._price = price;
MenuItem.count += 1;
}
static isValidPrice(price: number): boolean {
return Number.isInteger(price) && price >= 0;
}
get price(): number {
return this._price;
}
set price(newPrice: number) {
if (!MenuItem.isValidPrice(newPrice)) {
console.log("가격은 0 이상의 정수여야 합니다.");
return;
}
this._price = newPrice;
}
label(): string {
return `${this.name} ${this._price}원`;
}
}
const americano = new MenuItem("아메리카노", 4500);
const latte = new MenuItem("라떼", 5000);
latte.price = -100;
latte.price = 5200;
console.log(americano.label());
console.log(latte.label());
console.log(MenuItem.count);
class Order implements Describable {
private lines: { item: MenuItem; quantity: number }[] = [];
add(item: MenuItem, quantity: number): void {
if (!Number.isSafeInteger(quantity) || quantity <= 0) {
console.log("수량은 1 이상의 정수여야 합니다.");
return;
}
this.lines.push({ item: item, quantity: quantity });
}
get total(): number {
let sum = 0;
for (const line of this.lines) {
sum += line.item.price * line.quantity;
}
return sum;
}
label(): string {
return `주문 ${this.lines.length}건, 합계 ${this.total}원`;
}
}
const order = new Order();
order.add(americano, 2);
order.add(latte, 1);
order.add(latte, 0);
console.log(order.total);
interface Describable {
label(): string;
}
class SetMenu extends MenuItem {
constructor(name: string, price: number, private side: string) {
super(name, price);
}
override label(): string {
return `${super.label()} (${this.side} 포함)`;
}
}
function printLabels(things: Describable[]): void {
for (const thing of things) {
console.log(thing.label());
}
}
const lunchSet = new SetMenu("점심 세트", 8000, "샐러드");
order.add(lunchSet, 1);
printLabels([americano, lunchSet, order]);
abstract class Discount {
constructor(protected title: string) {}
apply(total: number): number {
const cut = Math.min(this.amount(total), total);
console.log(`${this.title}: ${cut}원 할인`);
return total - cut;
}
protected abstract amount(total: number): number;
}
class RateDiscount extends Discount {
constructor(private percent: number) {
super(`${percent}% 쿠폰`);
}
protected amount(total: number): number {
return Math.floor(total * this.percent / 100);
}
}
class FixedDiscount extends Discount {
constructor(private won: number) {
super(`${won}원 쿠폰`);
}
protected amount(total: number): number {
return this.won;
}
}
const discounts: Discount[] = [new RateDiscount(10), new FixedDiscount(3000), new FixedDiscount(30000)];
for (const discount of discounts) {
console.log(discount.apply(order.total));
}
interface Logger {
log(message: string): void;
warn(message: string): void;
error(message: string): void;
}
class MemoryLogger implements Logger {
readonly entries: string[] = [];
log(message: string): void {
this.entries.push(`INFO: ${message}`);
}
warn(message: string): void {
this.entries.push(`WARN: ${message}`);
}
error(message: string): void {
this.entries.push(`ERROR: ${message}`);
}
}
class Checkout {
constructor(private discount: Discount, private logger: Logger) {}
pay(target: Order): number {
if (target.total === 0) {
this.logger.warn("빈 주문은 결제하지 않습니다.");
return 0;
}
this.logger.log(`결제 시작: ${target.label()}`);
const amount = this.discount.apply(target.total);
this.logger.log(`결제 금액: ${amount}원`);
return amount;
}
}
const shopLogger = new MemoryLogger();
const checkout = new Checkout(new RateDiscount(10), shopLogger);
console.log(checkout.pay(order));
console.log(checkout.pay(new Order()));
console.log(shopLogger.entries.join(" | "));더 해 보기
Discount의apply가 콘솔에 직접 출력하는 대신Logger로 안내를 남기게 바꿉니다. 할인 계산 결과는 그대로 유지합니다.- 할인을 하지 않는
NoDiscount를 만들어 같은Checkout에 넘깁니다. 정상 주문은 22200원, 빈 주문은 0원이 되어야 합니다.
이것으로 4장의 클래스와 인터페이스를 마칩니다. 다음 장의 타입 가드와 타입 좁히기에서는 typeof와 in으로 값을 확인한 뒤 타입을 좁히고, 직접 타입 가드 함수를 만듭니다.