์ ๋ต ํจํด (Strategy)
- ์๊ณ ๋ฆฌ์ฆ์ ์ธํฐํ์ด์ค๋ก ๋ถ๋ฆฌํด์ ์ ์ฐํ๊ฒ ๊ต์ฒด ๊ฐ๋ฅ
// ์ ๋ต ํจํด
// => ๋ฐํ์ ์์ ์ ์๊ณ ๋ฆฌ์ฆ(์ ๋ต)์ ๊ต์ฒดํ ์ ์๋๋ก ํด์ค
// => Spring์์๋ ์ธํฐํ์ด์ค ๊ตฌํ์ฒด๋ค์ Bean์ผ๋ก ๋ฑ๋กํ๊ณ Map์ผ๋ก ์ฃผ์
๋ฐ์ ์ ์ฐํ๊ฒ ์ฒ๋ฆฌ
// ๊ฒฐ์ ๋ฐฉ์ ์ ํ ์์
// 1. ์ ๋ต ์ธํฐํ์ด์ค ์ ์
public interface PaymentStrategy {
void pay(int amount);
}
// 2. ์ ๋ต ๊ตฌํ์ฒด๋ค (@Component๋ก Bean๋ฑ๋ก)
@Component("card") // key๊ฐ์ด ๋๋ค (Map ์ฃผ์
์)
class CardPayment implements PaymentStrategy {
public void pay(int amount) {
System.out.println("Card๋ก " + amount + "์ ๊ฒฐ์ ");
}
}
@Component("Kakao")
class KakaoPay implements PaymentStrategy {
public void pay(int amount) {
System.out.println("Kakao pay๋ก " + amount + "์ ๊ฒฐ์ ");
}
}
// 3. ์ ๋ต์ map์ผ๋ก ์ฃผ์
๋ฐ์ ๋์ ์ผ๋ก ์ฌ์ฉ
@Service
public class PaymentService {
//์์กด์ฑ ์ถ๊ฐ
private final Map<String, PaymentStrategy> strategyMap;
// ๋ชจ๋ PaymanetStrategy Bean์ด ์ฃผ์
๋จ (key = @Component("name"))
public PaymentService(Map<String, PaymentStrategy> strategyMap) {
this.strategyMap = strategyMap;
}
public void pay(String method, int amount) {
PaymentStrategy strategy = strategyMap.get(method); // ex: "card", "kakao"
strategy.pay(amount); // ์ ๋ต์ ๋ฐ๋ผ ์คํ
}
}
@RestController
public class PaymentController {
// ์์กด์ฑ ์ถ๊ฐ
private final PaymentService paymentService;
public PaymentController(PaymentService paymentService) {
this.paymentService = paymentService;
}
// ex) /pay?method=card&amount=10000
@PostMapping("/pay")
public String pay(@RequestParam String method, @RequestParam int amount) {
paymentService.pay(method, amount);
return "๊ฒฐ์ ์๋ฃ";
}
}
'๋ฐฑ์๋(Back-End) ๊ฐ๋ฐ > Java' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[JAVA] ๋์์ธ ํจํด๋ค ์ ๋ฆฌ (0) | 2025.05.28 |
---|---|
[JAVA] ๋์์ธ ํจํด - ํ๋ก์ ํจํด(Proxy) (0) | 2025.05.28 |
[JAVA] ๋์์ธ ํจํด - ํฉํ ๋ฆฌ ๋ฉ์๋ ํจํด (Factory Method) (0) | 2025.05.28 |
[JAVA] ๋์์ธ ํจํด - ๋ธ๋ฆฟ์ง ํจํด(Bridge) (0) | 2025.05.28 |
[JAVA] ๋์์ธ ํจํด - ์ฑ๊ธํด ํจํด(Singleton) (0) | 2025.05.28 |