[Design Pattern] 9. ์ „๋žต ํŒจํ„ด(Strategy)

์—…๋ฐ์ดํŠธ:

์นดํ…Œ๊ณ ๋ฆฌ:

ํƒœ๊ทธ: ,




StrategyํŒจํ„ด

Strategy






์ „๋žต ํŒจํ„ด(Strategy)

๋“œ๋ก ๊ตฌํ˜„
๋“œ๋ก ์˜ ๋‹ค์–‘ํ•œ ๋™์ž‘์„ ๊ตฌํ˜„ํ•˜๋Š” ์ƒํ™ฉ
๋Ÿฐํƒ€์ž„์— ํŠน์ • ๋™์ž‘์„ ๊ฐ์ฒด์— ๋ฐ”๋กœ ํ• ๋‹นํ•  ์ˆ˜ ์žˆ์Œ

context : ์ž์‹ ์˜ ์ž‘์—…์„ ์ˆ˜ํ–‰ํ•˜๋Š”๋ฐ ํ•„์š”ํ•œ ์ „๋žต์„ ์„ ํƒํ•˜๋Š” ํด๋ž˜์Šค
strategy : ์ „๋žต ์ธํ„ฐํŽ˜์ด์Šค๋ฅผ ๊ตฌํ˜„ํ•œ ํด๋ž˜์Šค๋“ค๋กœ, ํŠน์ • ํ–‰๋™์„ ์ œ๊ณตํ•จ Client : ํด๋ผ์ด์–ธํŠธ์—์„œ context ํด๋ž˜์Šค๋ฅผ ์ƒ์„ฑ

image

์žฅ์ 
ย ย 1. ์บก์Šํ™” ์ž˜ ๋  ์ˆ˜ ์žˆ์Œ.
ย ย 2. ๋Ÿฐํƒ€์ž„์— ๊ฐ์ฒด๊ฐ€ ์‚ฌ์šฉํ•˜๋Š” ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ๊ตํ™˜ํ•  ์ˆ˜ ์žˆ์Œ.

์ „๋žต ํŒจํ„ด๊ณผ ์ƒํƒœํŒจํ„ด์ด ํ˜ผ๋™๋  ์ˆ˜ ์žˆ์Œ, ๊ตฌ์กฐ๊ฐ€ ์œ ์‚ฌํ•˜์ง€๋งŒ ์˜๋„๊ฐ€ ๋งค์šฐ ๋‹ค๋ฆ„.
์ „๋žต ํŒจํ„ด : ๊ฐ™์€ ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•˜๋Š” ์—ฌ๋Ÿฌ ์•Œ๊ณ ๋ฆฌ์ฆ˜์ด ์žˆ์„ ๋•Œ ์ด๋“ค ์ค‘ ํ•˜๋‚˜๋ฅผ ๋Ÿฐํƒ€์ž„์— ์„ ํƒํ•ด์•ผ ํ•  ๋•Œ, ์ฆ‰ ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์„ ํƒ์— ์ค‘์ 
์ƒํƒœ ํŒจํ„ด : ๊ฐ์ฒด๊ฐ€ ์—ฌ๋Ÿฌ ์ƒํƒœ๋ฅผ ๊ฐ€์ง€๊ณ  ์žˆ๊ณ , ์ƒํƒœ์— ๋”ฐ๋ผ ํ–‰๋™์ด ๋‹ฌ๋ผ์ ธ์•ผ ํ•  ๋•Œ. ์ฆ‰, ์ƒํƒœ์— ๋”ฐ๋ฅธ ํ–‰๋™ ๋ณ€๊ฒฝ

Drone
using UnityEngine;

public class Drone : MonoBehaviour {
    public void ApplyStrategy(IBehaviour strategy) {
        strategy.Maneuver(this);
    }
}
ClientStrategy
using UnityEngine;
using System.Collections.Generic;

public class ClientStrategy : MonoBehaviour {
    
    private GameObject _drone;
    private List<IBehaviour> 
        _components = new List<IBehaviour>();
    
    private void SpawnDrone() {
        _drone = 
            GameObject.CreatePrimitive(PrimitiveType.Cube);
        
        _drone.AddComponent<Drone>();
        
        _drone.transform.position = 
            Random.insideUnitSphere * 10;
        
        ApplyRandomStrategies();
    }

    private void ApplyRandomStrategies() {
        _components.Add(
            _drone.AddComponent<Weaving>());
        _components.Add(
            _drone.AddComponent<Bopping>());
        _components.Add(
            _drone.AddComponent<Fallback>());
        
        int index = Random.Range(0, _components.Count);
        
        _drone.GetComponent<Drone>().
            ApplyStrategy(_components[index]);
    }
    
    void OnGUI() {
        if (GUILayout.Button("Spawn Drone")) {
            SpawnDrone();
        }
    }
}








์žก๋‹ด, ์ •๋ฆฌ

  • ๋””์ž์ธ ํŒจํ„ด์€ ์• ์ดˆ์— ํŠน์ • ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•˜๊ธฐ ์œ„ํ•ด ๊ณ ๋ ค๋œ ๊ฒƒ.(์„ฑ๋Šฅ, ๋ฉ”๋ชจ๋ฆฌ ์‚ฌ์šฉ ๊ณ ๋ ค)
  • ์ถ”๊ฐ€ ๋‚ด์šฉ ์ •๋ฆฌ




[C#] ๋””์ž์ธ ํŒจํ„ด (Design Pattern)
TOP


๐Ÿ“”

๋Œ“๊ธ€๋‚จ๊ธฐ๊ธฐ