반응형
Factory Method Pattern과 Strategy Pattern
Factory Method Pattern과 Strategy Pattern은 둘 다 인터페이스(또는 추상 클래스) + 다형성을 이용하는 패턴이다.
그래서 처음 공부할 때 많이 헷갈린다.
하지만 목적이 완전히 다르다.
Factory Method Pattern
관심사 : "무엇을 만들까?"
Client
│
▼
Factory
│
├──► Dog
├──► Cat
└──► Tiger
인터페이스
public interface Animal {
void sound();
}
Factory
Animal animal = factory.create();
여기서 인터페이스는
객체를 생성한 후 어떤 타입으로 사용할 것인가
를 추상화하기 위해 존재한다.
Strategy Pattern
관심사 : "어떻게 동작할까?"
Client
│
▼
Context
│
├──► CardStrategy
├──► KakaoPayStrategy
└──► NaverPayStrategy
인터페이스
public interface PaymentStrategy {
void pay();
}
사용
strategy.pay();
여기서 인터페이스는
동작(알고리즘)을 교체하기 위해 존재한다.
둘 다 다형성을 이용한다.
Factory
Animal animal = factory.create();
실제로는
Dog
Cat
Tiger
중 하나가 생성된다.
Strategy
strategy.pay();
실제로는
CardPay
KakaoPay
NaverPay
중 하나의 로직이 실행된다.
가장 큰 차이
Factory Method
관심사 = 객체 생성
Factory
│
▼
new Dog()
생성 책임을 숨긴다.
Strategy Pattern
관심사 = 객체의 행동
PaymentStrategy
│
▼
pay()
행동을 교체한다.
실무 예제
Factory
Notification notification =
notificationFactory.create(type);
무슨 Notification을 만들지 결정.
Strategy
paymentStrategy.pay(order);
어떤 결제 방식을 사용할지 결정.
둘을 같이 사용하는 경우도 많다.
예를 들어
Client
│
▼
PaymentStrategyFactory
│
├──► CardStrategy
├──► KakaoStrategy
└──► NaverStrategy
Factory가
PaymentStrategy strategy =
factory.create("KAKAO");
를 통해 Strategy 객체를 생성하고,
그 다음
strategy.pay();
를 호출한다.
즉,
Factory Pattern
│
▼
Strategy 객체 생성
│
▼
Strategy Pattern
│
▼
실제 동작 수행
이렇게 함께 사용되는 경우가 매우 많다.
기억하기 쉬운 한 줄
- Factory Method Pattern : "어떤 객체를 만들지 결정하는 패턴"
- Strategy Pattern : "만들어진 객체가 어떤 방식으로 동작할지 결정하는 패턴"
둘 다 인터페이스와 다형성을 사용하지만,
- Factory는 생성(Creation)
- Strategy는 행동(Behavior)
을 추상화한다는 점이 가장 큰 차이이다.
반응형
'language > java' 카테고리의 다른 글
| 번외편 - Java Comparator vs JavaScript sort() (0) | 2026.06.04 |
|---|---|
| List.of에 대하여 (0) | 2026.06.01 |
| Factory Method Pattern (팩토리 메서드 패턴) (0) | 2026.06.01 |
| Static Factory Method (정적 팩토리 메서드) (0) | 2026.06.01 |
| Virtual Thread (Java 21) 완벽 이해하기 (0) | 2026.06.01 |
댓글