apple/DesignPattern & Architecture

[Swift] Strategy Pattern

lgvv 2022. 4. 11. 02:05

Strategy Pattern

 

✅ Strategy Pattern

 

아래의 문서를 구입하여 영어 문서를 번역하고 이해한 것을 바탕으로 글을 작성하고 있습니다.

https://www.raywenderlich.com/books/design-patterns-by-tutorials/v3.0/chapters/5-strategy-pattern

 

Design Patterns by Tutorials, Chapter 5: Strategy Pattern

The strategy pattern defines a family of interchangeable objects that can be set or switched at runtime: the object using a strategy, the strategy protocol, and the set of strategies. You continue to build out RabbleWabble and learn how these three compone

www.raywenderlich.com

 

 

Strategy Pattern

Strategy 패턴은 런타임에 설정하거나 전환할 수 있는 교환 가능한 객체 제품군을 정의한다. 이 패턴에는 세 가지 부분이 있다.

 

Strategy pattern

 

🟠 Object using a strategy : 이것은 iOS 앱개발에서 패턴이 사용될 떄 가장 흔히 사용되는 패턴이지만, 기술적으로 동작이 필요한 모든 종류의 객체일 수 있다.

🟠 strategy protocol : strategy protocol은 구현해야하는 모든 strategy 메소드를 정의한다.

🟠 strategies : strategies는 strategy protocol을 준수(conform)하는 객체이다.

 

✅ When should you use it?

서로 교환할 수 있는 두 가지 이상의 서로 다른 패턴이 있을 때 전략 패턴을 사용한다.

 

이 패턴은 delegation pattern과 유사하다. 두 패턴 모두 유연성 향상을 위해 구체적인 객체 대신 프로토콜에 의존한다. 결과적으로 straregy protocol을 구현하는 any 객체들은 런타임시에 strategy에 사용될 수 있다.

 

delegation 패턴과 다르게 strategy 패턴은 objects의 family로 사용한다.

 

delegates는 종종 런타임시에 고정된다. 예를들면 UITableView를 위한 dataSoure와 delegate는 Interface Builder로 세팅될 수 있다. 그리고 런타임 시에 변경되는 경우는 드물다.

 

하지만, Strategies는 런타임시에 쉽게 교환될 수 있도록 의도되었다.

 

✅ 코드

https://github.com/lgvv/DesignPattern/tree/main/strategy-pattern/RabbleWabble

 

GitHub - lgvv/DesignPattern: ✨ 디자인 패턴을 공부합니다!

✨ 디자인 패턴을 공부합니다! Contribute to lgvv/DesignPattern development by creating an account on GitHub.

github.com

 

 

✅ 여기부터는 이해를 돕기 위한 부분

 

Strategy는 한국말로 전략이라고 번역되어서 전략 패턴이라고 불린다.

근데 전략 패턴 ..? 바로 이해가 가지 않았다. 런타임시에 쉽게 교환될 수 있다라 .. 흠...

 

소스 파일 구조도

위의 파일 구조도에서 Strategies 부분을 보자.

 

QuestionStrategy.swift

import Foundation

public protocol QuestionStrategy: class {
  var title: String { get }
  
  var correctCount: Int { get }
  var incorrectCount: Int { get }
  
  func advanceToNextQuestion() -> Bool
  func currentQuestion() -> Question
  
  func markQuestionCorrect(_ question: Question)
  func markQuestionIncorrect(_ question: Question)
  
  func questionIndexTitle() -> String
}

하나의 전략을 프로토콜로 만들어 둔다.

 

아래의 클래스 다이어그램은 전략 패턴을 사용하는 부분만 간략히 추린 부분이다.

SelectrQuestionViewController는 원하는 프로토콜을 직접 상속받아 구현하는 것이 아니라, 이미 클래스로 구현되어 있는 전략을 교체하므로써 코드의 유연성을 높인다.

 

위의 코드에서 전략을 교체하는 부분은 

SelectQuestionGroupViewController.swift - prepare 메소드에 위치하고 있다.

 

전략 패턴의 사용 방법

이렇게 할 경우 장점은 새로운 것들이 나올 때마다 ViewController에 if-else문을 통하여 분기를 통해 구현해주는 것이 아닌, 전략을 교체하므로써 코드의 유연성을 높이고 개발자의 생산성을 높일 수 있다.

 

 

 

 

(참고)

https://victorydntmd.tistory.com/292

 

[디자인패턴] 전략 패턴 ( Strategy Pattern )

전략 패턴 ( Strategy Pattern ) 객체들이 할 수 있는 행위 각각에 대해 전략 클래스를 생성하고, 유사한 행위들을 캡슐화 하는 인터페이스를 정의하여, 객체의 행위를 동적으로 바꾸고 싶은 경우

victorydntmd.tistory.com