๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ—‚๏ธ ์Šคํ„ฐ๋”” ํ™œ๋™/๐Ÿ“— ๋ฉด์ ‘์„ ์œ„ํ•œ CS ์ „๊ณต์ง€์‹ ๋…ธํŠธ

[๋””์ž์ธํŒจํ„ด] ์ „๋žต ํŒจํ„ด

by ๐Ÿ’พ๊ณ ๊ตฌ๋งˆ๋ง›ํƒ•๋จน๊ณ ์‹ถ๋‹ค 2024. 9. 10.
728x90

๊ฐ์ฒด์˜ ํ–‰์œ„๋ฅผ ํด๋ž˜์Šค๋ฅผ ํ†ตํ•ด ์บก์Šํ™”ํ•˜์—ฌ ๋™์ ์œผ๋กœ ํ–‰์œ„๋ฅผ ๋ณ€๊ฒฝํ•  ์ˆ˜ ์žˆ๊ฒŒ ํ•ด์ฃผ๋Š” ํŒจํ„ด

 

์žฅ์ :

  • ์ฝ”๋“œ์˜ ์œ ์—ฐ์„ฑ : ์„œ๋กœ ๋‹ค๋ฅธ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์‰ฝ๊ฒŒ ๊ต์ฒดํ•  ์ˆ˜ ์žˆ์œผ๋ฏ€๋กœ, ์ฝ”๋“œ์˜ ์œ ์—ฐ์„ฑ ๋†’์•„์ง
  • ์žฌ์‚ฌ์šฉ์„ฑ : ํŠน์ • ํ–‰๋™(์ „๋žต)์„ ๋ณ„๋„์˜ ํด๋ž˜์Šค๋กœ ๋ถ„๋ฆฌํ•จ์œผ๋กœ์จ ์—ฌ๋Ÿฌ ๊ฐ์ฒด์—์„œ ์žฌ์‚ฌ์šฉ
  • ๋Ÿฐํƒ€์ž„์—์„œ ์ „๋žต ์„ ํƒ : ์ธํ„ฐํŽ˜์ด์Šค๋ฅผ ํ†ตํ•ด ๋‹ค์–‘ํ•œ ์•Œ๊ณ ๋ฆฌ์ฆ˜(์ „๋žต)์„ ๊ตฌํ˜„ ๊ฐ€๋Šฅ, ์ด๋ฅผ ๋Ÿฐํƒ€์ž„์— ์„ ํƒํ•˜๊ฑฐ๋‚˜ ๊ต์ฒด

๋‹จ์ :

  • ํด๋ž˜์Šค ์ˆ˜ ์ฆ๊ฐ€ : ํด๋ž˜์Šค๋กœ ๋ถ„๋ฆฌํ•˜์—ฌ ํด๋ž˜์Šค์˜ ์ˆ˜ ์ฆ๊ฐ€ํ•จ. ์ด๋กœ์ธํ•ด ์ฝ”๋“œ ๋ณต์žกํ•ด์ง
  • ํด๋ผ์ด์–ธํŠธ ์ฝ”๋“œ์˜ ๋ณต์žก์„ฑ : ๊ฐ์ฒด ์ƒ์„ฑ ๋ฐ ๊ด€๋ฆฌ ๋กœ์ง ์ถ”๊ฐ€๋จ
  • ์˜์กด์„ฑ ์ฆ๊ฐ€ : ์ž˜๋ชป ์„ค๊ณ„ ์‹œ ์œ ์ง€๋ณด์ˆ˜ ์–ด๋ ค์›€

https://integu.net/strategy-pattern/

์˜ˆ์‹œ ์ฝ”๋“œ

# ์ „๋žต
class MusicStrategy:
    def recommend_song(self):
        pass

# ๋ฐœ๋ผ๋“œ
class Ballad(MusicStrategy):
    def recommend_song(self):
        return "Recommended Song: Ballad"

# ํž™ํ•ฉ
class HipHop(MusicStrategy):
    def recommend_song(self):
        return "Recommended Song: HipHop"

# ์ปจํ…์ŠคํŠธ ํด๋ž˜์Šค
class User:
    def __init__(self, strategy: MusicStrategy):
        self._strategy = strategy

    def recommend(self):
        return self._strategy.recommend_song()

user1 = User(Ballad())
print(user1.recommend())  # ๋ฐœ๋ผ๋“œ ์ถ”์ฒœ

user2 = User(HipHop())
print(user2.recommend())  # ํž™ํ•ฉ ์ถ”์ฒœ

 

728x90