Fabryka (ang. factory) jest wzorcem projektowym, który umożliwia tworzenie różnego typu obiektów za pomocą jednej metody dostępowej.

Jeżeli obiekty klas pochodnych mają być tworzone tylko za pomocą wzorca fabryki, należy uprywatnić ich konstruktory i zaprzyjaźnić z klasą bazową lub z metodą tworzącą obiekty (CTire::Create).


#include <iostream>

class CTire
{
public:
    enum Type
    {
       Winter, Summer
    };

public:
    static CTire* Create(Type type);

public:
    virtual void Roll() = 0;
};

class CWinterTire : public CTire
{
    CWinterTire() {}
    friend class CTire;
public:
    virtual void Roll()
    {
       std::cout << "Winter tire is rolling." << std::endl;
    }
};

class CSummerTire : public CTire
{
    CSummerTire() {}
    friend class CTire;
public:
    virtual void Roll()
    {
       std::cout << "Summer tire is rolling." << std::endl;
    }
};

CTire* CTire::Create(Type type)
{
    switch (type)
    {
    case Winter:
        return new CWinterTire();
    case Summer:
        return new CSummerTire();
    }

    return NULL;
}

int main(int nArguments, char* szArguments[])
{
    CTire* aTires[] = {
        CTire::Create(CTire::Summer),
        CTire::Create(CTire::Winter),
    };

    int nTires = sizeof(aTires) / sizeof(aTires[0]);

    for (int nIndex = 0; nIndex < nTires; nIndex++)
        aTires[nIndex]->Roll();

    return 0;
}


0 Komentarzy

Dodaj komentarz

Twój adres e-mail nie zostanie opublikowany. Wymagane pola są oznaczone *