GoF์˜ ๋””์ž์ธ ํŒจํ„ด, ์ „๋žต ํŒจํ„ด์— ๋Œ€ํ•ด ์•Œ์•„๋ณธ๋‹ค.

ํ•ด๋‹น ๊ธ€์€, ๋‹ค์Œ์˜ ์ฝ”๋“œ๋ฅผ ๊ธฐ๋ฐ˜์œผ๋กœ ์ดํ•ดํ•˜๋Š” ๊ฒƒ์ด ํŽธ๋ฆฌํ•ฉ๋‹ˆ๋‹ค.

ํ•ต์‹ฌ ์š”์•ฝ

  • ์‹คํ–‰ ์ค‘์— ๊ธฐ๋Šฅ์„ ๋ณ€๊ฒฝํ•ด์•ผ ํ•˜๋Š” ๊ฒฝ์šฐ ์‚ฌ์šฉ

์˜ˆ์‹œ

Code

main

//
//  main.swift
//  Strategy
//
//  Created by Choiwansik on 2023/02/13.
//
 
import Foundation
 
internal func main() {
    let printer = SumPrinter()
 
    printer.printValue(with: SimpleSumStrategy(), n: 10)
 
    printer.printValue(with: GaussSumStrategy(), n: 10)
}
 
main()
 
 

SumPrinter

//
//  SumPrinter.swift
//  Strategy
//
//  Created by Choiwansik on 2023/02/13.
//
 
import Foundation
 
internal class SumPrinter {
 
    internal func printValue(with strategy: SumStrategy, n: Int) {
        print("1์—์„œ \(n)๊นŒ์ง€์˜ ํ•ฉ")
        print(strategy.calculate(with: n))
    }
 
}
 

SumStrategy

//
//  SumStrategy.swift
//  Strategy
//
//  Created by Choiwansik on 2023/02/13.
//
 
import Foundation
 
internal protocol SumStrategy {
 
    func calculate(with n: Int) -> Int
 
}
 

SimpleSumStrategy

//
//  SimpleSumStrategy.swift
//  Strategy
//
//  Created by Choiwansik on 2023/02/13.
//
 
import Foundation
 
internal class SimpleSumStrategy: SumStrategy {
 
    internal func calculate(with n: Int) -> Int {
        (1...n).reduce(.zero, +)
    }
 
}
 

GaussSumStrategy

//
//  GaussSumStrategy.swift
//  Strategy
//
//  Created by Choiwansik on 2023/02/13.
//
 
import Foundation
 
internal class GaussSumStrategy: SumStrategy {
 
    internal func calculate(with n: Int) -> Int {
        (n+1)*n / 2
    }
 
}

ํ™œ์šฉ์„ฑ

  • ์•Œ๊ณ ๋ฆฌ์ฆ˜์˜ ๋ณ€ํ˜•์ด ํ•„์š”ํ•  ๋•Œ (์—ฌ๋Ÿฌ๊ฐœ ์ผ ๋•Œ)

๊ฒฐ๊ณผ

  • ์žฅ์ 
    • ์กฐ๊ฑด๋ฌธ์„ ์—†์•จ ์ˆ˜ ์žˆ๋‹ค.
    • ์„œ๋ธŒํด๋ž˜์‹ฑ์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š์„ ์ˆ˜ ์žˆ๋‹ค.
    • ์•Œ๊ณ ๋ฆฌ์ฆ˜์˜ ์ž์‚ฌ์šฉ์ด ๊ฐ€๋Šฅํ•˜๋‹ค.
    • ๊ตฌํ˜„์˜ ์„ ํƒ์ด ๊ฐ€๋Šฅํ•˜๋‹ค.
  • ๋‹จ์ 
    • ํด๋ผ์ด์–ธํŠธ๋Š” ์„œ๋กœ ๋‹ค๋ฅธ ์ „๋žต๋“ค์— ๋Œ€ํ•ด ์ดํ•ดํ•ด์•ผ ํ•œ๋‹ค. (์žฅ๋‹จ์ ์— ๋Œ€ํ•ด)
    • Strategy์™€ Context ์‚ฌ์ด์˜ ์˜์‚ฌ์†Œํ†ต ์˜ค๋ฒ„ํ—ค๋“œ๊ฐ€ ์ƒ๊ธด๋‹ค. ๊ฒฐํ•ฉ๋„๊ฐ€ ๋†’์•„์งˆ ์ˆ˜ ์žˆ๋‹ค.
    • ๊ฐ์ฒด์ˆ˜๊ฐ€ ์ฆ๊ฐ€ํ•œ๋‹ค.

์ƒ๊ฐํ•ด๋ณผ ์ 

  • ์ตœ์ ํ™”๊ฐ€ ํ•„์š”ํ•œ ๋ถ€๋ถ„์— ๋Œ€ํ•ด ์ด๋Ÿฐ ํŒจํ„ด์„ ์‚ฌ์šฉํ•˜๋ฉด ์ข‹์„ ๊ฒƒ ๊ฐ™๋‹ค.
  • ์•Œ๊ณ ๋ฆฌ์ฆ˜์˜ ์žฅ๋‹จ์ ์ด ๋ช…ํ™•ํ•˜๋‹ค๋ฉด, ๊ตฌํ˜„์ฒด๋ฅผ ๋‘ ๊ฐœ ๋‘๊ณ  ์ƒํ™ฉ์— ๋”ฐ๋ผ ์„ ํƒํ•˜๋„๋ก ๋งŒ๋“ค๋ฉด ์ข‹๊ฒ ๋‹ค.

Reference