Strategy Pattern(전략)은 Algorithm Family를 정의하고 각 알고리즘을 캡슐화 한 뒤 런타임에서 알고리즘을 서로 바꿔 사용할 수 있는 디자인 패턴

장점
단점
Strategy 인터페이스 역할을 할 프로토콜을 하나 정의
// Strategy
protocol Strategy {
func algorithmExecute()
}
Strategy 프로토콜을 채택하는 알고리즘 생성 → Concrete strategy
// Concrete Strategy
class CarRoute: Strategy {
func algorithmExecute() {
print("자동차 경로 찾기 완료!\n")
}
}
// Concrete Strategy
class WalkRoute: Strategy {
func algorithmExecute() {
print("도보 경로 찾기 완료!\n")
}
}
// Concrete Strategy
class BikeRoute: Strategy {
func algorithmExecute() {
print("자전거 경로 찾기 완료!\n")
}
}
알고리즘들을 교체해가며 사용할 Context를 구현
// Context
class Navigation {
private var routeAlgorithm: Strategy?
func execute() {
self.routeAlgorithm?.algorithmExecute()
}
func setStrategy(strategy: Strategy) {
self.routeAlgorithm = strategy
}
}
사용
let navigation = Navigation()
navigation.setStrategy(strategy: CarRoute())
navigation.execute()
navigation.setStrategy(strategy: WalkRoute())
navigation.execute()
navigation.setStrategy(strategy: BikeRoute())
navigation.execute()
// 자동차 경로 찾기 완료!
// 도보 경로 찾기 완료!
// 자전거 경로 찾기 완료!