Click here to Skip to main content
15,881,588 members
Articles / General Programming
Article

Factory Pattern in C++

Rate me:
Please Sign up or sign in to vote.
4.88/5 (61 votes)
15 Sep 2012CPOL2 min read 345.5K   3.2K   88   65
Using the Factory pattern in C++ to expose only an object's abstract type--hiding the implementation class detail.

Overview

Up until now, I never really used the Factory pattern that often in C++. Recently, I found a use for it in a project I was working on and since I found it useful for my purposes, I thought I might share a tutorial on how the Factory pattern can be used in C++.

Disclaimer: Now I’m not entirely sure how closely my model fits the typical Factory pattern but as far as I understand the Factory pattern, it is pretty close if not exact.

Definition 

Basically a Factory consists of an interface class which is common to all of the implementation classes that the factory will create. Then you have the factory class which is usually a singleton class that spawns instances of these implementation classes.

Abstract Interface Class

So let us create a quick interface class to start with. In this example, I used IAnimal

C++
class IAnimal
{
public:
    virtual int GetNumberOfLegs() const = 0;
    virtual void Speak() = 0;
    virtual void Free() = 0;
}; 

Now for simplicity’s sake, I used a typedef to define a type for the function that is used by the implementation classes to create instances of IAnimal. This typedef is also used in declaring the map that maps the animal name to the function that creates that particular type of animal. You can use whatever calling convention you like, but for this example, I chose __stdcall.

C++
typedef IAnimal* (__stdcall *CreateAnimalFn)(void); 

Specific Implementation Class(es) 

Now come the implementation classes. These are the classes that implement the IAnimal interface. Here’re a few examples:

C++
// IAnimal implementations
class Cat : public IAnimal
{
public:
    int GetNumberOfLegs() const { return 4; }
    void Speak() { cout << "Meow" << endl; }
    void Free() { delete this; }

    static IAnimal * __stdcall Create() { return new Cat(); }
};

class Dog : public IAnimal
{
public:
    int GetNumberOfLegs() const { return 4; }
    void Speak() { cout << "Woof" << endl; }
    void Free() { delete this; }

    static IAnimal * __stdcall Create() { return new Dog(); }
};

class Spider : public IAnimal // Yeah it isn’t really an animal…
{
public:
    int GetNumberOfLegs() const { return 8; }
    void Speak() { cout << endl; }
    void Free() { delete this; }

    static IAnimal * __stdcall Create() { return new Spider(); }
};

class Horse : public IAnimal
{
public:
    int GetNumberOfLegs() const { return 4; }
    void Speak() { cout << "A horse is a horse, of course, of course." << endl; }
    void Free() { delete this; }

    static IAnimal * __stdcall Create() { return new Horse(); }
};

Factory Class Declaration 

Now comes the Factory class. This is a singleton pattern implementation--meaning only one instance of the factory can ever be instantiated, no more, no less.

C++
// Factory for creating instances of IAnimal
class AnimalFactory
{
private:
    AnimalFactory();
    AnimalFactory(const AnimalFactory &) { }
    AnimalFactory &operator=(const AnimalFactory &) { return *this; }

    typedef map FactoryMap;
    FactoryMap m_FactoryMap;
public:
    ~AnimalFactory() { m_FactoryMap.clear(); }

    static AnimalFactory *Get()
    {
        static AnimalFactory instance;
        return &instance;
    }

    void Register(const string &animalName, CreateAnimalFn pfnCreate);
    IAnimal *CreateAnimal(const string &animalName);
};

Factory Class Implementation

Now we need to work out a few definitions of the AnimalFactory class. Specifically the constructor, the Register, and the CreateAnimal functions.

Constructor

The constructor is where you might consider registering your Factory functions. Though this doesn’t have to be done here, I’ve done it here for the purposes of this example. You could for instance register your Factory types with the Factory class from somewhere else in the code.

C++
/* Animal factory constructor.
Register the types of animals here.
*/
AnimalFactory::AnimalFactory()
{
    Register("Horse", &Horse::Create);
    Register("Cat", &Cat::Create);
    Register("Dog", &Dog::Create);
    Register("Spider", &Spider::Create);
}

Type Registration

Now let us implement the Register function. This function is pretty straightforward since I used a std::map to hold the mapping between my string (the animal type) and the create function.

C++
void AnimalFactory::Register(const string &animalName, CreateAnimalFn pfnCreate)
{
    m_FactoryMap[animalName] = pfnCreate;
}

Type Creation

And last but not least, the CreateAnimal function. This function accepts a string parameter which corresponds to the string registered in the AnimalFactory constructor. When this function receives “Horse” for example, it will return an instance of the Horse class, which implements the IAnimal interface.

C++
IAnimal *AnimalFactory::CreateAnimal(const string &animalName)
{
    FactoryMap::iterator it = m_FactoryMap.find(animalName);
    if( it != m_FactoryMap.end() )
    return it->second();
    return NULL;
}

Example Usage Program

C++
int main( int argc, char **argv )
{
    IAnimal *pAnimal = NULL;
    string animalName;

    while( pAnimal == NULL )
    {
        cout << "Type the name of an animal or ‘q’ to quit: ";
        cin >> animalName;

        if( animalName == "q" )
        break;

        IAnimal *pAnimal = AnimalFactory::Get()->CreateAnimal(animalName);
        if( pAnimal )
        {
            cout << "Your animal has " << pAnimal->GetNumberOfLegs() << " legs." << endl;
            cout << "Your animal says: ";
            pAnimal->Speak();
        }
        else
        {
            cout << "That animal doesn’t exist in the farm! Choose another!" << endl;
        }
        if( pAnimal )
            pAnimal->Free();
        pAnimal = NULL;
        animalName.clear();
    }
    return 0;
}
This article was originally posted at http://www.caledunlap.com/2010/10/factory-pattern-in-c

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
United States United States
I'm an interactive software and web developer by day and a video game developer by night. I hold an Associate's degree in Computer Information Systems, a Bachelor's degree in Game and Simulation Programming, and have been writing various types of software since 1999.

The programming languages in which I am experienced include C, C++, C#, PHP, and JavaScript--just to name a few. I have experience in creating mobile, embedded, desktop, command-line/console, web, and video game applications for consumer, business, and government/defense purposes.

Comments and Discussions

 
QuestionAAnimal pool Pin
armagedescu26-Apr-12 23:59
armagedescu26-Apr-12 23:59 
AnswerRe: Animal pool Pin
Cosmore21-May-12 3:36
Cosmore21-May-12 3:36 
AnswerRe: Animal pool Pin
dagronf15-Sep-12 13:23
dagronf15-Sep-12 13:23 
GeneralMessage Closed Pin
16-Sep-12 21:19
armagedescu16-Sep-12 21:19 
GeneralRe: Animal pool Pin
dagronf16-Sep-12 22:26
dagronf16-Sep-12 22:26 
GeneralMessage Closed Pin
17-Sep-12 3:24
armagedescu17-Sep-12 3:24 
GeneralRe: Animal pool Pin
dagronf17-Sep-12 12:32
dagronf17-Sep-12 12:32 
Question__stdcall Pin
KjellKod.cc21-Apr-12 22:28
KjellKod.cc21-Apr-12 22:28 
I am a little puzzled by the use of __stdcall. Do you actually have to specify that, or any WIN API calling order? Why would it not work with standard C++?

C++
Example: 
static IAnimal * __stdcall Create() { return new Cat(); }


Working more with Qt Windows/Linux I have not used it myself but thought the purpose was to use for:
(from stackoverflow[^])
"any calls to Windows APIs, and callbacks from Windows APIs, must use the __stdcall convention"

In your example above I do not see any Windows specific API. Why not just skip the __stdcall? Please enlighten me.

modified 22-Apr-12 4:37am.

AnswerRe: __stdcall Pin
Eytukan26-Apr-12 21:01
Eytukan26-Apr-12 21:01 
AnswerRe: __stdcall Pin
KjellKod.cc26-Apr-12 21:21
KjellKod.cc26-Apr-12 21:21 
AnswerRe: __stdcall Pin
waleri26-Apr-12 21:31
waleri26-Apr-12 21:31 
GeneralRe: __stdcall Pin
Eytukan26-Apr-12 21:42
Eytukan26-Apr-12 21:42 
QuestionFactory pattern Pin
geoyar16-Apr-12 10:37
professionalgeoyar16-Apr-12 10:37 
AnswerRe: Factory pattern Pin
AmirAlilou7-Jun-12 4:38
AmirAlilou7-Jun-12 4:38 
AnswerRe: Factory pattern Pin
dagronf17-Sep-12 12:54
dagronf17-Sep-12 12:54 
QuestionI like this. Pin
phillipvoyle16-Apr-12 9:04
phillipvoyle16-Apr-12 9:04 
QuestionWell explained Pin
Nelek12-Apr-12 13:43
protectorNelek12-Apr-12 13:43 
AnswerRe: Well explained Pin
ftai15-Apr-12 22:18
ftai15-Apr-12 22:18 
Questionauto register ? Pin
Chunlong lin11-Apr-12 3:21
Chunlong lin11-Apr-12 3:21 
AnswerRe: auto register ? Pin
wan.rui@qq.com9-May-12 23:16
wan.rui@qq.com9-May-12 23:16 
QuestionVoted 5 Pin
prashu10010-Apr-12 20:40
prashu10010-Apr-12 20:40 
QuestionSimple and to the point Pin
Nathan Going10-Apr-12 6:50
Nathan Going10-Apr-12 6:50 
QuestionNice! Pin
Chunlong lin10-Apr-12 2:48
Chunlong lin10-Apr-12 2:48 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.