[Design Pattern] Strategy Pattern

[Design Pattern] Strategy Pattern

Strategy pattern

์ผ๋ช…, ์ „๋žตํŒจํ„ด

๋ชฉ์ 

  • ๊ฐ๊ฐ์„ ์บก์Šํ™”ํ•˜์—ฌ ๋ณ€ํ™” ๊ฐ€๋Šฅํ•˜๊ฒŒ ๋งŒ๋“  ์•Œ๊ณ ๋ฆฌ์ฆ˜์˜ ์ง‘ํ•ฉ์„ ์ •์˜ํ•œ๋‹ค.
  • ์ธํ„ฐํŽ˜์ด์Šค์— ์ถ”์ƒ ๋ฉ”์†Œ๋“œ๋ฅผ ์ •์˜ํ•˜๊ณ , ์ž์„ธํ•œ ๊ตฌํ˜„์€ ํŒŒ์ƒ๋œ ํด๋ž˜์Šค์— ํ•œ๋‹ค.
  • Strategy ํŒจํ„ด์€ ์•Œ๊ณ ๋ฆฌ์ฆ˜์ด ๊ทธ๊ฒƒ์„ ์‚ฌ์šฉํ•˜๋Š” ํด๋ผ์ด์–ธํŠธ์™€ ๋…๋ฆฝ์ ์œผ๋กœ ๋ณ€ํ™”ํ•  ์ˆ˜ ์žˆ๊ฒŒ ํ•ด์ค€๋‹ค. โž” OCP

OCP(Open-Closed Principle;๊ฐœ๋ฐฉ ํ์‡„ ์›์น™) ํ™•์žฅ์—๋Š” ์—ด๋ ค์žˆ๊ณ , ์ˆ˜์ •์—๋Š” ๋‹ซํ˜€ ์žˆ์–ด์•ผ ํ•œ๋‹ค๋Š” ๊ฐ์ฒด ์ง€ํ–ฅ ํ”„๋กœ๊ทธ๋ž˜๋ฐ์˜ ํ•ต์‹ฌ ์›์น™

ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๋Š” ๋ฌธ์ œ

ํด๋ผ์ด์–ธํŠธ๋Š” ๋ณ€ํ™”์™€ ๊ด€๋ จํ•ด์„œ ์‹ ๊ฒฝ์“ฐ์ง€ ์•Š์•„์•ผ ํ•œ๋‹ค.
โž” ํŒŒ์ƒ๋œ ํด๋ž˜์Šค ์ˆ˜๊ฐ€ ๋ณ€ํ–ˆ์„ ๊ฒฝ์šฐ, ํŒŒ์ƒ๋œ ํด๋ž˜์Šค์˜ ๊ตฌํ˜„์ด ๋ฐ”๋€Œ์—ˆ์„ ๊ฒฝ์šฐ์— ๋Œ€ํ•œ ์˜ํ–ฅ์ด ์—†์–ด์•ผ ํ•œ๋‹ค.

๊ตฌ์กฐ

Inline-image-2018-01-22 16.15.23.146.png

2๊ฐ€์ง€ ๊ตฌํ˜„ ๋ฐฉ๋ฒ•

  1. Abstract base class
    Interface entity(์œ„ ๊ตฌ์กฐ์—์„œ์˜ Interface)๋ฅผ abstract base class๋กœ ๋‚˜ํƒ€๋‚ธ๋‹ค.
    โž” ์ƒ์† ๊ณ„์ธต์ด ๋™์ ์ธ ๋‹คํ˜•์„ฑ์„ ๋‚˜ํƒ€๋‚ธ๋‹ค.

  2. ํด๋ผ์ด์–ธํŠธ์— ์˜ํ•œ method signature(method name + parameters) ์˜ˆ์ธก
    โž” ์ด ๊ฒฝ์šฐ Interface entity๋Š” ํด๋ผ์ด์–ธํŠธ์—์„œ template code๊ฐ€ ๋˜๊ณ , ์ƒ์† ๊ณ„์ธต์€ ์ •์ ์ธ ๋‹คํ˜•์„ฑ์„ ๋‚˜ํƒ€๋‚ธ๋‹ค.
    (์ด ๋ฐฉ๋ฒ•์€ ์ž˜ ๋ชจ๋ฅด๊ฒ ์Œ.. ๋‹ค์‹œ ์ฐพ์•„๋ณผ ๊ฒƒ)

์˜ˆ์ œ

์ฝ”๋“œ ์˜ˆ์ œ๋กœ ์„ค๋ช…์ด ์ž˜ ๋˜์–ด์žˆ๋Š” ๊ธ€
(Abstract base class ๋ฐฉ๋ฒ•์œผ๋กœ ๊ตฌํ˜„ํ•œ ์˜ˆ์ œ)

๋‹ค๋ฅธ ํŒจํ„ด๋“ค๊ณผ์˜ ๋น„๊ต

  • Strategy ํŒจํ„ด์€ ์ƒ์„ธํ•˜๊ฒŒ ๋‚˜๋ˆ„๋Š” ์ •๋„๋ฅผ ์ œ์™ธํ•˜๋ฉด Template-method ํŒจํ„ด๊ณผ ๋น„์Šทํ•˜๋‹ค. strategy vs template method

  • State, Strategy, Bridge ํŒจํ„ด์€ ๋น„์Šทํ•œ ๊ตฌ์กฐ๋ฅผ ๊ฐ€์ง€์ง€๋งŒ ๋ชฉ์ ์€ ๋ชจ๋‘ ๋‹ค๋ฅด๋‹ค.
    โž” ์ฆ‰, ๊ฐ๊ฐ ๋‹ค๋ฅธ ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•˜๊ธฐ ์œ„ํ•œ ๋ฐฉ๋ฒ•

  • Strategy ํŒจํ„ด์˜ ์ฒซ๋ฒˆ์งธ ๊ตฌํ˜„ ๋ฐฉ๋ฒ•(Abstract base class)์€ State ํŒจํ„ด๊ณผ ์œ ์‚ฌํ•˜๋‹ค.

    • ์ฐจ์ด์ : Strategy ํŒจํ„ด์€ ํ•œ๋ฒˆ ๋ฐ”์ธ๋”ฉ๋˜๊ณ , State ํŒจํ„ด์€ ๋™์ ์œผ๋กœ ์—ฌ๋Ÿฌ๋ฒˆ ๋ฐ”์ธ๋”ฉ๋œ๋‹ค.

    โž” Strategy ํŒจํ„ด์ด ์ข€ ๋” ๊ฐ€๋ณ๋‹ค๊ณ  ํ•  ์ˆ˜ ์žˆ๋‹ค.



[Reference]
Design Patterns Explained Simply - Alexander Shvets
http://jdm.kr/blog/54
http://www.bitesizedcsharp.com/

Comments