본문 바로가기
Design Patterns

[Design Patterns] (Abstract) Factory Pattern

by matters_ 2021. 8. 6.

(Abstract) Factory Pattern

Factory method를 사용하여 직접적으로 객체 class를 사용하지 않고 객체를 생성하는 생성 패턴

creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created.

Purpose

객체 생성 함수를 노출시키고 subclass가 실제로 생성하도록 하도록 합니다.

Exposes a method for creating objects, allowing subclasses to control the actual creation process.

Use When

  • 어떤 Class가 생성될 필요성이 있을지 모를 때
    A class will not know what classes it will be required to create.
  • Subclass가 어떤 객체를 만들지 결정할 필요성이 있을 때
    Subclasses may specify what objects should be created.
  • Parent class가 subclass의 생성을 미루고 싶을 때
    Parent classes wish to defer creation to their subclasses.

UML

Plant_Hello

Example Code

#include <iostream>
#include <string>
#include <map>
using namespace std;

struct Food
{
    virtual void prepare(int volume) = 0;
};

struct Sandwich : Food
{
    void prepare(int volume) override
    {
        cout << "This is Sandwich, volume : " << volume << " pieces"<<"\n";
    }
};

struct Cake : Food
{
    void prepare(int volume) override
    {
        cout << "This is Cake, volume : " << volume << " pieces"<<"\n";
    }
};

struct BakeryFactory 
{
    virtual Food* make() = 0;
};

struct SandwichFactory : BakeryFactory
{
public:
    Food* make() override
    {
        return new Sandwich;
    }
};

struct CakeFactory : BakeryFactory
{
public:
    Food* make() override
    {
        return new Cake;
    }
};

class FoodFactory
{
    map<string, BakeryFactory*> bakery_factories;
public:
    FoodFactory()
    {
        bakery_factories["sandwich"] = new SandwichFactory();
        bakery_factories["cake"] = new CakeFactory();
    }

    ~FoodFactory()
    {
        delete  bakery_factories["sandwich"];
        delete  bakery_factories["cake"];
    }

    Food* make_food(const string& name, int vol)
    {
        auto food = bakery_factories[name]->make();
        food->prepare(vol);
        return food;
    }

};

int main()
{
    FoodFactory food_factory;
    food_factory.make_food("cake",5);
    food_factory.make_food("sandwich",2);

    return 0;
}

Output

Reference

https://en.wikipedia.org/wiki/Factory_method_pattern

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

[Design Patterns] Strategy Pattern  (0) 2021.07.30
[Design Patterns] Composite Pattern  (0) 2021.07.26

댓글