Back
Download the header File
// Allen Kennedy Jr.
// gets rid of all those nasty STL warnings
#pragma warning(disable:4786)
#include <string>
#include <map>
#include <iostream>
using namespace std;
//
// The Abstract class
//
class AbstractClass
{
public:
// this is the Type definition to a pointer to a member function of this class
// That takes a input parameter of a integer
typedef AbstractClass* (*PTRF)(int);
virtual int getVar() = 0;
};
//
// A derived class
//
class DerivedClass1 : public AbstractClass
{
public:
// this static member function is used to create one of these objects and give back a pointer to it
static AbstractClass* create(int V) { return new DerivedClass1(V); }
DerivedClass1(int Var): DerivedClass1Var( Var ){}
virtual int getVar()
{
return DerivedClass1Var;
}
private:
int DerivedClass1Var;
};
//
// Another derived class
//
class DerivedClass2 : public AbstractClass
{
public:
static AbstractClass* create(int V)
{
return new DerivedClass2(V);
}
DerivedClass2(int Var) : DerivedClass2Var( Var ){}
virtual int getVar()
{
return DerivedClass2Var;
}
private:
int DerivedClass2Var;
};
//
// The Factory that makes Derived classes
//
class Factory
{
public:
// Setup the classes for the factory to create
static Initialize()
{
theConstructorMap[ "DerivedClass1" ] = DerivedClass1::create;
theConstructorMap[ "DerivedClass2" ] = DerivedClass2::create;
}
// create and return a class named "Name" with a default argument
static AbstractClass* MakeObject( string Name, int ConstructorArg = 3)
{
return theConstructorMap[ Name ](ConstructorArg);
}
private:
static map < string, AbstractClass::PTRF > theConstructorMap;
};
// Static member variable initialization for the Factory
map < string, AbstractClass::PTRF > Factory::theConstructorMap;
int main(int argc, char* argv[])
{
Factory::Initialize();
AbstractClass* ptr;
ptr = Factory::MakeObject("DerivedClass1", 6); // create one with an argument
cout << "Class1 with arg 6 gives me " << ptr->getVar() << endl;
delete ptr; // don't forget to delete an bject when you are done with it
ptr = Factory::MakeObject("DerivedClass1"); // create one without an argument
cout << "Class1 with no arg gives me " << ptr->getVar() << endl;
delete ptr; // don't forget to delete an bject when you are done with it
ptr = Factory::MakeObject("DerivedClass2"); // Create a different one
cout << "Class2 with no arg gives me " << ptr->getVar() << endl;
delete ptr; // don't forget to delete an bject when you are done with it
return 0;
}
