갓똥
나는야 프로그래머
갓똥
전체 방문자
오늘
어제
  • 분류 전체보기 (186)
    • 프로그래밍 (146)
      • 자바 (9)
      • 안드로이드 (2)
      • 유니티 (20)
      • C++ (38)
      • C# (56)
      • HTML (2)
      • 파이썬 (3)
      • 자료구조 (2)
      • 알고리즘 (0)
      • 문제풀이 (4)
      • 디자인 패턴 (7)
      • 카카오톡 봇 (1)
      • 엑셀 (1)
      • 기타 (1)
    • 게임 (21)
      • 테일즈위버 (0)
      • 카이로소프트 (1)
      • 순위 (19)
      • 기타 (1)
    • 일상 (13)
      • 카페 (1)
      • 방탈출 (12)
    • 기타 (6)
      • 웃긴자료 (5)

블로그 메뉴

  • 홈
  • 방명록

공지사항

인기 글

태그

  • 롤 골드그래프
  • 전세계 게임 매출
  • 자바
  • Unity Graph
  • C++ 상속
  • c# delegate
  • C++
  • 게임 디자인 패턴
  • c# Thread
  • pc 게임 순위
  • pc게임 순위
  • c# 코루틴
  • 글로벌게임매출
  • 유니티 골드그래프
  • 모바일 게임 순위
  • 게임 매출 순위
  • 알고리즘
  • 2020년 게임 매출
  • C# 예외 처리
  • c# collection
  • 게임매출순위
  • C++ 소멸자
  • c# coroutine
  • 유니티 그래프
  • C++ virtual
  • C# boxing
  • 전세계게임매출순위
  • 유니티 그래프 그리기
  • c# unboxing
  • 강남 방탈출

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
갓똥

나는야 프로그래머

심플 팩토리 패턴 (Simple Factory Pattern)
프로그래밍/디자인 패턴

심플 팩토리 패턴 (Simple Factory Pattern)

2020. 5. 24. 16:00
728x90
반응형

팩토리란? (Factory)

    => 객체 생성을 처리하는 클래스

 

심플 팩토리란? (Simple Factory)

    => 객체를 생성하는 일을 전담하는 클래스

 

심플 팩토리 패턴 정의

    => 일반적인 팩토리 패턴은 무언가 객체를 생성하고자 할 때 사용하는 패턴

    => 심플 팩토리는 사실 패턴이라기보다는 객체지향 프로그램을 할 때 사용되는 관용구 같은 것

    => 하지만 팩토리 메서드 패턴이나, 추상 팩토리 패턴의 기본이므로 알아두면 좋음

    => 주어진 입력을 기반으로 다른 유형의 객체를 반환하는 메소드가 있는 팩토리 클래스

 

이제 유니티에서 코드를 통해 패턴을 확인해보려고 한다.

유닛을 영역에 맞게 생성하고 로그로 움직임을 찍어보려고 한다.

 

프로젝트 구성은 아래와 같다.

 

먼저 Unit.cs이다.

// Unit.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public abstract class Unit : MonoBehaviour
{
    public abstract void Move();
}

추상 클래스로 Unit이 있다.

이 추상 클래스는 Move라는 추상메서드가 있다.

 

// Player.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : Unit
{
    void Start()
    {
        Debug.Log("플레이어 캐릭터 생성");
    }
    
    public override void Move()
    {
        Debug.Log("플레이어 캐릭터 이동!");
    }
}

// Enemy1.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Enemy1 : Unit
{
    void Start()
    {
        Debug.Log("적 몬스터1 생성");
    }

    public override void Move()
    {
        Debug.Log("적 몬스터1 이동!");
    }
}

// Enemy2.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Enemy2 : Unit
{
    void Start()
    {
        Debug.Log("적 몬스터2 생성");
    }

    public override void Move()
    {
        Debug.Log("적 몬스터2 이동!");
    }
}

다음은 Player.cs, Enemy1.cs, Enemy2.cs 이다.

각각 Unit을 상속받아 추상 메소드인 Move를 구현하고 있다.

 

// FactoryUnit.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public enum UnitType
{
    Player,
    Enemy1,
    Enemy2
}

public class FactoryUnit : MonoBehaviour
{
    public GameObject player = null;
    public GameObject enemy1 = null;
    public GameObject enemy2 = null;

    public GameObject createUnit(UnitType type)
    {
        GameObject unit = null;

        float x;
        float z;

        switch(type)
        {
            case UnitType.Player:
                x = (float)Random.Range(-4, 0);
                z = (float)Random.Range(-4, 4);
                unit = Instantiate(player, new Vector3(x, 0.0f, z), Quaternion.identity);
                break;
            case UnitType.Enemy1:
                x = (float)Random.Range(0, 4);
                z = (float)Random.Range(0, 4);
                unit = Instantiate(enemy1, new Vector3(x, 0.0f, z), Quaternion.identity);
                break;
            case UnitType.Enemy2:
                x = (float)Random.Range(0, 4);
                z = (float)Random.Range(-4, 0);
                unit = Instantiate(enemy2, new Vector3(x, 0.0f, z), Quaternion.identity);
                break;
        }

        return unit;
    }
}

FactoryUnit.cs는 GameManager를 통해 createUnit메소드를 호출하면 각 타입에 맞는 오브젝트를 생성시켜주는 클래스이다.

 

// FactoryUse.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FactoryUse : MonoBehaviour
{
    FactoryUnit factory = null;
    GameObject player = null;
    GameObject enemy1 = null;
    GameObject enemy2 = null;

    void Start()
    {
        factory = GetComponent<FactoryUnit>();

        player = factory.createUnit(UnitType.Player);
        enemy1 = factory.createUnit(UnitType.Enemy1);
        enemy2 = factory.createUnit(UnitType.Enemy2);
        
        StartCoroutine("UnitMove");
    }

    IEnumerator UnitMove()
    {
        // 추상클래스 Unit을 이용하여 Player, Enemy의 구분없이 접근하여 사용가능
        while(true) { 
            yield return new WaitForSeconds(2.0f);
            
            player.GetComponent<Unit>().Move();
            enemy1.GetComponent<Unit>().Move();
            enemy2.GetComponent<Unit>().Move();
        }
    }
}

마지막으로 FactoryUse.cs이다.

 

여기에서는 FactoryUnit.cs가 심플 팩토리 패턴이라고 할 수 있다.

FactoryUse를 통해 각 생성 타입을 넘겨주고

FactoryUnit의 createUnit을 통해 넘겨 받은 타입을 생성한다.

그렇게 생성된 객체들은 바로 접근 가능하다.

 

실행 시 각 영역에 생성된 모습이다.

생성 후 2초간격으로 움직이는 것을 볼 수 있다.

지금은 로그를 찍었지만 실제 움직이게 하는것도 가능하다.

728x90
반응형

'프로그래밍 > 디자인 패턴' 카테고리의 다른 글

추상 팩토리 패턴 (Abstract Factory Pattern)  (0) 2020.05.31
팩토리 메서드 패턴 (Factory Method Pattern)  (0) 2020.05.26
스트레티지 패턴 (Strategy Pattern)  (0) 2020.05.20
싱글턴 패턴 (Singleton Pattern)  (0) 2020.05.19
컴포넌트 패턴 (Component Pattern)  (0) 2020.05.17
    '프로그래밍/디자인 패턴' 카테고리의 다른 글
    • 추상 팩토리 패턴 (Abstract Factory Pattern)
    • 팩토리 메서드 패턴 (Factory Method Pattern)
    • 스트레티지 패턴 (Strategy Pattern)
    • 싱글턴 패턴 (Singleton Pattern)
    갓똥
    갓똥
    공부하며 알아가는 내용을 정리해 봅니다.

    티스토리툴바