๋ฐ์ํ
์ ๋ต ํจํด์ด๋?
๋์ผํ ๊ธฐ๋ฅ์ ์ฌ๋ฌ ๋ฐฉ์(์ ๋ต)์ผ๋ก ๊ตฌํํด๋๊ณ ,
์ํฉ์ ๋ฐ๋ผ ๋ฐ๊ฟ์ ์ฌ์ฉํ ์ ์๊ฒ ํ๋ ํจํด
์ค๋ฌด ๋น์
์๋ฅผ ๋ค์ด, ๊ฒฐ์ ์๋น์ค๊ฐ ์๋ค๊ณ ํ์.
- ์นด์นด์คํ์ด ๊ฒฐ์
- ๋ค์ด๋ฒํ์ด ๊ฒฐ์
- Toss ๊ฒฐ์
์ ๋ต๋ง๋ค ๊ตฌํ์ด ๋ค๋ฅด์ง๋ง, ์ฌ์ฉ์๋ “๊ฒฐ์ ํ๋ค”๋ ๊ธฐ๋ฅ๋ง ์์ฒญํ๋ฉด ๋๋ค.
Spring Boot์์๋ ์ด๋ ๊ฒ ์ ์ฉ๋จ
1. ๊ณตํต ์ธํฐํ์ด์ค ์ ์
public interface PayStrategy {
void pay(int amount);
}
2.์ ๋ต ๊ตฌํ์ฒด ๋ง๋ค๊ธฐ
@Component("kakaoPay")
public class KakaoPayStrategy implements PayStrategy {
public void pay(int amount) {
System.out.println("์นด์นด์คํ์ด๋ก " + amount + "์ ๊ฒฐ์ ");
}
}
@Component("naverPay")
public class NaverPayStrategy implements PayStrategy {
public void pay(int amount) {
System.out.println("๋ค์ด๋ฒํ์ด๋ก " + amount + "์ ๊ฒฐ์ ");
}
}
3.์ฃผ์ ๋ฐ์์ ์คํ
@Service
public class PayService {
private final Map<String, PayStrategy> strategyMap;
public PayService(Map<String, PayStrategy> strategyMap) {
this.strategyMap = strategyMap;
}
public void pay(String method, int amount) {
PayStrategy strategy = strategyMap.get(method);
if (strategy != null) strategy.pay(amount);
else throw new IllegalArgumentException("์ง์ํ์ง ์๋ ๊ฒฐ์ ๋ฐฉ์: " + method);
}
}
4.์ปจํธ๋กค๋ฌ์์ ํธ์ถ
@RestController
@RequiredArgsConstructor
public class PayController {
private final PayService payService;
@PostMapping("/pay")
public void pay(@RequestParam String method, @RequestParam int amount) {
payService.pay(method, amount);
}
}
์คํ ์์
POST /pay?method=kakaoPay&amount=1000
→ ์นด์นด์คํ์ด๋ก 1000์ ๊ฒฐ์
POST /pay?method=naverPay&amount=2000
→ ๋ค์ด๋ฒํ์ด๋ก 2000์ ๊ฒฐ์
Spring์ด ์ ๋ต ํจํด์ ๋ ํธํ๊ฒ ํด์ฃผ๋ ์ด์
| ๊ธฐ๋ฅ | ์ค๋ช |
| @Component | ์๋์ผ๋ก Bean ๋ฑ๋ก (์ ๋ต ๊ตฌํ์ฒด ์ฝ๊ฒ ๋ฑ๋ก๋จ) |
| Map<String, Interface> ์ฃผ์ | ์ ๋ต ์ด๋ฆ ↔ ์ ๋ต ๊ฐ์ฒด ์ฐ๊ฒฐ ์๋ ์ฒ๋ฆฌ๋จ |
| DI + IoC | ์ ์ฐํ ํ์ฅ ๊ฐ๋ฅ (์ ์ ๋ต ์ถ๊ฐ๋ง ํ๋ฉด ๋) |
์ฃผ์ํ ์
- ์ ๋ต ์ด๋ฆ(@Component("kakaoPay"))์ ์ค์ํ๋ฉด ์ฃผ์ ์ ๋จ
- strategyMap.get(...)์ ๋ฐฉ์ด ๋ก์ง ํ์
- ์ธํฐํ์ด์ค๊ฐ ๋๋ฌด ๋ณต์กํด์ง๋ฉด ์คํ๋ ค ์ ์ง๋ณด์ ์ด๋ ค์์ง
์ ๋ต ํจํด์ “๋ก์ง์ ๊ฐ์ ๋ผ์ฐ๋ ์ค๊ณ”
์คํ๋ง์์๋ Map<String, ์ ๋ต>๋ง ๋ฐ์๋ ๋ฐ๋ก ์ ๋ต ํจํด์ด ๋๋ค!
๋ฐ์ํ