๐Ÿ“š Computer Science/Design Pattern

[Unity][๋””์ž์ธ ํŒจํ„ด] Simple Factory Pattern(์‹ฌํ”Œ ํŒฉํ† ๋ฆฌ ํŒจํ„ด)

ibelieveinme 2023. 9. 13. 23:59
728x90

*Factory: ๊ฐ์ฒด ์ƒ์„ฑ์„ ์ฒ˜๋ฆฌํ•˜๋Š” ํด๋ž˜์Šค๋ฅผ ํŒฉํ† ๋ฆฌ๋ผ๊ณ  ๋ถ€๋ฅธ๋‹ค.

*Simple Factory: ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•˜๋Š” ์ผ์„ ์ „๋‹ดํ•˜๋Š” ํด๋ž˜์Šค.

 

Simple Factory Pattern ์—๋Š” ์ฃผ์–ด์ง„ ์ž…๋ ฅ์„ ๊ธฐ๋ฐ˜์œผ๋กœ ๋‹ค๋ฅธ ์œ ํ˜•์˜ ๊ฐ์ฒด๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ๋ฉ”์†Œ๋“œ๊ฐ€ ์žˆ๋Š” ํŒฉํ† ๋ฆฌ ํด๋ž˜์Šค๊ฐ€ ์žˆ๋‹ค.

 

Simple Factory ๋Š” ๊ฐ์ฒด์ง€ํ–ฅ ํ”„๋กœ๊ทธ๋ž˜๋ฐ์„ ํ•  ๋•Œ ํ•ญ์ƒ ์‚ฌ์šฉํ•˜๋Š” ๋ฐฉ๋ฒ•์ด๋ผ ํŒจํ„ด์œผ๋กœ ์ทจ๊ธ‰ํ•˜์ง€๋Š” ์•Š๋Š”๋‹ค.

๋‹ค๋งŒ, ํŒฉํ† ๋ฆฌ ๋ฉ”์„œ๋“œ ํŒจํ„ด์ด๋‚˜ ์ถ”์ƒ ํŒฉํ† ๋ฆฌ ํŒจํ„ด์˜ ๊ธฐ๋ณธ์ด ๋˜๊ธฐ ๋•Œ๋ฌธ์— ์•Œ์•„๋‘์ž.

 

using UnityEngine;


public abstract class Unit
{
    public abstract void move();
}

public class Marine : Unit
{
    public Marine()
    {
        Debug.Log("Marine ์ƒ์„ฑ");
    }

    public override void move()
    {
        Debug.Log("Marine ์ด๋™");
    }
}

public class Firebat : Unit
{
    public Firebat()
    {
        Debug.Log("Firebat ์ƒ์„ฑ");
    }

    public override void move()
    {
        Debug.Log("Firebat ์ด๋™");
    }
}

public class Madic : Unit
{
    public Madic()
    {
        Debug.Log("Madic ์ƒ์„ฑ");
    }

    public override void move()
    {
        Debug.Log("Madic ์ด๋™");
    }
}

Unit ์ถ”์ƒ ํด๋ž˜์Šค๋ฅผ ์ƒ์†๋ฐ›๊ณ  Unit ์ถ”์ƒํด๋ž˜์Šค์˜  move ์ถ”์ƒ ๋ฉ”์†Œ๋“œ๋ฅผ ๊ฐ€์ง„ Marine, Firebat, Madic ํด๋ž˜์Šค๊ฐ€ ์žˆ๋‹ค.

 

public enum UnitType
{
    Marine,
    Firebat,
    Madic
}

public class UnityFactory
{
    public static Unit createUnit(UnitType unitType)
    {
        Unit unit = null;

        switch (unitType)
        {
            case UnitType.Marine:
                unit = new Marine();
                break;
            case UnitType.Firebat:
                unit = new Firebat();
                break;

            case UnitType.Madic:
                unit = new Madic();
                break;
        }
        return unit;
    }
}

UnitFactory ํด๋ž˜์Šค๋Š” UnitType ์— ๋งž์ถฐ์„œ ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•˜๊ณ  ๋ฐ˜ํ™˜ํ•œ๋‹ค.

์ด๋ ‡๊ฒŒ ๊ฐ์ฒด๋ฅผ ์ƒ์„ฑํ•˜๋Š” ๋ถ€๋ถ„๋งŒ์„ ๋˜‘ ๋–ผ์–ด์„œ ํด๋ž˜์Šค๋กœ ๋งŒ๋“œ๋Š” ๋ฐฉ๋ฒ•์ด Simple Factory ํŒจํ„ด์ด๋‹ค.

 

using UnityEngine;

public class FactoryUse : MonoBehaviour
{
    void Start()
    {
        Unit unit1 = UnityFactory.createUnit(UnitType.Marine);
        Unit unit2 = UnityFactory.createUnit(UnitType.Firebat);
        Unit unit3 = UnityFactory.createUnit(UnitType.Madic);

        unit1.move();
        unit2.move();
        unit3.move();
    }
}

UnitFactory ํด๋ž˜์Šค๋ฅผ ์‚ฌ์šฉํ•  ๋‹ค๋ฅธ ํด๋ž˜์Šค์—์„œ Unit ์„ ๋งŒ๋“ค๊ณ  move ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•ด์ค€ ๋ชจ์Šต์ด๋‹ค. 

728x90