Factory Pattern

Yongs12 ㅣ 2024. 2. 2. 19:26

팩토리 패턴 예시 (Enemy)

#pragma once

/*=================================
		Factory Pattern
=================================*/

/*
객체를 생성하는 인터페이스를 정의하고 구체적인 객체는 서브클래스에 생성하도록 하는 패턴

장점
ㄴ 유연성 : 객체 생성 로직을 중앙 집중화 시킨다.
ㄴ 추상화 : 구체적인 클래스에 의존하지 않아 다양한 구현체에 적용 가능
ㄴ 확장성: 기존 코드에 영향을 주지 않고 새로운 팩토리 클래스를 확장할 수 있다.

단점
ㄴ 복잡성 : 작은 프로젝트에서는 팩토리 클래스로 인해 불필요한 복잡성이 생길 수 있음.
ㄴ 가독성 : 객체 생성을 위한 추상화가 많아져 가독성을 떨어뜨릴 수 있음.
*/

enum class EnemyType : __int16
{
	GOBLIN,
	ORC
};

class Enemy
{
public:
	Enemy() {}
	Enemy(int hp, int mp)
		: _hp(hp)
		, _mp(mp)
	{}

	virtual ~Enemy() {}

	// 공통적으로 사용할 순수 가상 함수
	virtual void attack() = 0; 

	void setHp(int hp)
	{
		_hp = hp;
	}

	int getHp() const
	{
		return _hp;
	}

	void setMp(int mp)
	{
		_mp = mp;
	}

	int getMp() const
	{
		return _mp;
	}

private:
	int _hp = 0;
	int _mp = 0;
};

class Goblin : public Enemy 
{
public:
	Goblin() {}
	Goblin(int hp, int mp) 
		: Enemy(hp, mp) 
	{}

	void attack() override 
	{
		cout << "Goblin Attack" << endl;
	}
};

class Orc : public Enemy
{
public:
	Orc() {}
	Orc(int hp, int mp) : Enemy(hp, mp) {}

	void attack() override
	{
		cout << "Orc Attack" << endl;
	}
};

 

EnemyFactory에서 객체 생성

#pragma once
#include "Enemy.h"

/*
여러 Enemy들을 팩토리에서 생성
*/
class EnemyFactory
{
public:
	static unique_ptr<Enemy> createEnemy(const EnemyType type)
	{
		switch (type)
		{
		case EnemyType::GOBLIN:
			return make_unique<Goblin>();
		case EnemyType::ORC:
			return make_unique<Orc>();
		default:
			return nullptr;
		}
	}
};

 

팩토리 사용

#include "pch.h"
#include "EnemyFactory.h"

int main()
{
	unique_ptr<Enemy> goblin = EnemyFactory::createEnemy(EnemyType::GOBLIN);
	unique_ptr<Enemy> orc = EnemyFactory::createEnemy(EnemyType::ORC);

	goblin->attack();
	orc->attack();

	return 0;
}

 

 

'Design Pattern' 카테고리의 다른 글

State Pattern  (0) 2024.02.06
Observer Pattern  (0) 2024.02.05
Prototype Pattern  (0) 2024.02.04
Builder Pattern  (0) 2024.02.03
Singleton Pattern  (0) 2024.02.01