๐Ÿ“š Computer Science/Design Pattern

[C#][Unity][๋””์ž์ธ ํŒจํ„ด] Strategy Pattern(์ „๋žต ํŒจํ„ด)

ibelieveinme 2023. 9. 5. 11:47
728x90

*Strategy Pattern: ์—ฌ๋Ÿฌ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ํ•˜๋‚˜์˜ ์ถ”์ƒ์ ์ธ ์ ‘๊ทผ์ (์ธํ„ฐํŽ˜์ด์Šค)์„ ๋งŒ๋“ค์–ด์„œ ์ ‘๊ทผ์ ์—์„œ ์•Œ๊ณ ๋ฆฌ์ฆ˜์ด ์„œ๋กœ ๊ตํ™˜ ๊ฐ€๋Šฅํ•˜๋„๋ก ํ•˜๋Š” ํŒจํ„ด

 

*์‚ฌ์šฉ ์˜ˆ: ์›Œ๋“œ ๋ฌธ์„œ์—์„œ ํ”„๋ฆฐํ„ฐ, ํฐํŠธ ์‚ฌ์šฉ. ์–ด๋–ค ๊ธฐ์ข…์˜ ํ”„๋ฆฐํŠธ๋”๋ผ๋„ 'Print' ๋ฒ„ํŠผ๋งŒ ๋ˆ„๋ฅด๋ฉด ๋˜‘๊ฐ™์ด ๋™์ž‘ํ•จ.

               ๊ฒŒ์ž„ ์บ๋ฆญํ„ฐ์˜ ๋ฌด๊ธฐ(๊ต์ฒด ํ›„) ์‚ฌ์šฉ. ์–ด๋–ค ๋ฌด๊ธฐ๋ผ๋„ '๊ณต๊ฒฉ' ๋ฒ„ํŠผ๋งŒ ๋ˆ„๋ฅด๋ฉด ๊ณต๊ฒฉ ๋™์ž‘์„ ์ˆ˜ํ–‰ํ•จ.

 

public class MyWeapon
{
    //์ ‘๊ทผ์ 
    private IWeapon weapon;

    //๋ฌด๊ธฐ ์ฒด์ธ์ง€
    public void SetWeapon(IWeapon weapon)
    {
        this.weapon = weapon;
    }

    //๋ฌด๊ธฐ์‚ฌ์šฉ
    public void Shoot()
    {
        weapon.Shoot();
    }
}

IWeapon ์ธํ„ฐํŽ˜์ด์Šค๋ฅผ ์—ฐ๊ฒฐํ•˜๋Š” MyWeapon ํด๋ž˜์Šค๋ฅผ ๋งŒ๋“ ๋‹ค.

MyWeapon ํด๋ž˜์Šค์—๋Š” SetWeapon ํ•จ์ˆ˜์™€ Shoot ํ•จ์ˆ˜๊ฐ€ ์žˆ๋‹ค.

SetWeapon ํ•จ์ˆ˜์—” IWeapon ์ธํ„ฐํŽ˜์ด์Šค๊ฐ€ ์ธ์ž๋กœ ์—ฐ๊ฒฐ๋œ๋‹ค.

Shoot ํ•จ์ˆ˜๊ฐ€ ์‹คํ–‰๋  ๋•, IWeapon ์ธํ„ฐํŽ˜์ด์Šค์˜ Shoot ํ•จ์ˆ˜๊ฐ€ ์‹คํ–‰๋œ๋‹ค.

 

//์ธํ„ฐํŽ˜์ด์Šค
public interface IWeapon
{
    void Shoot();
}

 

using UnityEngine;

public class Arrow : IWeapon
{
    public void Shoot()
    {
        Debug.Log("Arrow Attack");
    }
}

์ธํ„ฐํŽ˜์ด์Šค์— ์žˆ๋Š” Shoot ํ•จ์ˆ˜๋ฅผ Arrow ํด๋ž˜์Šค์—์„œ ๊ตฌ์ฒด์ ์œผ๋กœ ๊ตฌํ˜„ํ•จ.

using UnityEngine;

public class Bullet : IWeapon
{
    public void Shoot()
    {
        Debug.Log("Bullet Attack"); 
    }
}

์ธํ„ฐํŽ˜์ด์Šค์— ์žˆ๋Š” Shoot ํ•จ์ˆ˜๋ฅผ Bullet ํด๋ž˜์Šค์—์„œ ๊ตฌ์ฒด์ ์œผ๋กœ ๊ตฌํ˜„ํ•จ.

 

using UnityEngine;

public class WeaponManager : MonoBehaviour
{
    MyWeapon myWeapon;

    private void Start()
    {
        myWeapon = new MyWeapon();
        myWeapon.SetWeapon(new Bullet());
    }

    //๋ฌด๊ธฐ ๋ณ€๊ฒฝ
    public void ChangeBullet()
    {
        myWeapon.SetWeapon(new Bullet());
    }

    //๋ฌด๊ธฐ ๋ณ€๊ฒฝ
    public void ChangeArrow()
    {
        myWeapon.SetWeapon(new Arrow());
    }

    //๋ฌด๊ธฐ ์‚ฌ์šฉ
    public void Attack()
    {
        myWeapon.Shoot();
    }
}

Bullet, Arrow ๊ฐ์ฒด์˜ ๋ฒ„ํŠผ์„ ChangeBullet(), ChangeArrow() ํ•จ์ˆ˜์— ์—ฐ๊ฒฐํ•œ๋‹ค.

MyWeapon ํด๋ž˜์Šค์˜ SetWeapon() ํ•จ์ˆ˜๊ฐ€ ์‹คํ–‰๋  ๋•Œ, IWeapon ์ธํ„ฐํŽ˜์ด์Šค๋ฅผ ์ƒ์†๋ฐ›์€ ๊ฐ์ฒด๋“ค์ด ๊ฐ๊ฐ ์ „๋‹ฌ๋œ๋‹ค.(์ ‘๊ทผ์ )

Attack ๊ฐ์ฒด์˜ ๋ฒ„ํŠผ์„ ๋ˆ„๋ฅด๋ฉด Attack() ํ•จ์ˆ˜๊ฐ€ ์‹คํ–‰๋˜๊ณ  ๋ฌด๊ธฐ์— ํ•ด๋‹น๋˜๋Š” Shoot() ํ•จ์ˆ˜๊ฐ€ ์‹คํ–‰๋œ๋‹ค.

 

์ฆ‰, ์‚ฌ์šฉ์ž๋Š” ๋‹จ์ง€ ๋ฌด๊ธฐ๋ฅผ ๋ฐ”๊พธ๊ณ  Attack() ๋งŒ ์‹คํ–‰ํ•˜๋ฉด ๊ฐ ๋ฌด๊ธฐ์— ํ•ด๋‹นํ•˜๋Š” ๊ณต๊ฒฉ์„ ์ˆ˜ํ–‰ํ•  ์ˆ˜ ์žˆ๋‹ค.

 

 

728x90