//: C10:ShapeFactory2.cpp
// Polymorphic Factory Methods
#include <iostream>
#include <map>
#include <stdexcept>
#include <string>
#include <vector>
#include "../purge.h"
using namespace std;
class Shape {
public:
virtual void draw() = 0;
virtual void erase() = 0;
virtual ~Shape() {}
};
class ShapeFactory {
virtual Shape* create() = 0;
static map<string, ShapeFactory*> factories;
public:
virtual ~ShapeFactory() {}
friend class ShapeFactoryInitializer;
class BadShapeCreation : public logic_error {
public:
BadShapeCreation(string type)
: logic_error("Cannot create type " + type)
{}
};
static Shape*
createShape(const string& id) throw(BadShapeCreation){
if(factories.find(id) != factories.end())
return factories[id]->create();
else
throw BadShapeCreation(id);
}
};
// Define the static object:
map<string, ShapeFactory*>
ShapeFactory::factories;
class Circle : public Shape {
Circle() {} // Private constructor
public:
void draw() { cout << "Circle::draw\n"; }
void erase() { cout << "Circle::erase\n"; }
~Circle() { cout << "Circle::~Circle\n"; }
private:
friend class ShapeFactoryInitializer;
class Factory;
friend class Factory;
class Factory : public ShapeFactory {
public:
Shape* create() { return new Circle; }
friend class ShapeFactoryInitializer;
};
};
class Square : public Shape {
Square() {}
public:
void draw() { cout << "Square::draw\n"; }
void erase() { cout << "Square::erase\n"; }
~Square() { cout << "Square::~Square\n"; }
private:
friend class ShapeFactoryInitializer;
class Factory;
friend class Factory;
class Factory : public ShapeFactory {
public:
Shape* create() { return new Square; }
friend class ShapeFactoryInitializer;
};
};
// Singleton to initialize the ShapeFactory:
class ShapeFactoryInitializer {
static ShapeFactoryInitializer si;
ShapeFactoryInitializer() {
ShapeFactory::factories["Circle"] =
new Circle::Factory;
ShapeFactory::factories["Square"] =
new Square::Factory;
}
~ShapeFactoryInitializer() {
delete ShapeFactory::factories["Circle"];
delete ShapeFactory::factories["Square"];
}
};
// Static member definition:
ShapeFactoryInitializer
ShapeFactoryInitializer::si;
char* shlist[] = { "Circle", "Square", "Square",
"Circle", "Circle", "Circle", "Square", "" };
int main() {
vector<Shape*> shapes;
try {
for(char** cp = shlist; **cp; cp++)
shapes.push_back(
ShapeFactory::createShape(*cp));
} catch(ShapeFactory::BadShapeCreation e) {
cout << e.what() << endl;
return 1;
}
for(size_t i = 0; i < shapes.size(); i++) {
shapes[i]->draw();
shapes[i]->erase();
}
purge(shapes);
} ///:~
Now the Factory Method appears in its own class, ShapeFactory, as the virtual create( ). This is a private member function, which means it cannot be called directly but can be overridden. The subclasses of Shape must each create their own subclasses of ShapeFactory and override the create( ) member function to create an object of their own type. These factories are private, so that they are only accessible from the main Factory Method. This way, all client code must go through the Factory Method in order to create objects.
The actual creation of shapes is performed by calling ShapeFactory::createShape( ), which is a static member function that uses the map in ShapeFactory to find the appropriate factory object based on an identifier that you pass it. The factory is immediately used to create the shape object, but you could imagine a more complex problem in which the appropriate factory object is returned and then used by the caller to create an object in a more sophisticated way. However, it seems that much of the time you don’t need the intricacies of the polymorphic Factory Method, and a single static member function in the base class (as shown in ShapeFactory1.cpp) will work fine.
Notice that the ShapeFactory must be initialized by loading its map with factory objects, which takes place in the Singleton ShapeFactoryInitializer. So to add a new type to this design you must define the type, create a factory, and modify ShapeFactoryInitializer so that an instance of your factory is inserted in the map. This extra complexity again suggests the use of a static Factory Method if you don’t need to create individual factory objects.
Abstract factories
The Abstract Factory pattern looks like the factory objects we’ve seen previously, with not one but several Factory Methods. Each of the Factory Methods creates a different kind of object. The idea is that when you create the factory object, you decide how all the objects created by that factory will be used. The example in Design Patterns implements portability across various graphical user interfaces (GUIs): you create a factory object appropriate to the GUI that you’re working with, and from then on when you ask it for a menu, a button, a slider, and so on, it will automatically create the appropriate version of that item for the GUI. Thus, you’re able to isolate, in one place, the effect of changing from one GUI to another.
As another example, suppose you are creating a general-purpose gaming environment and you want to be able to support different types of games. Here’s how it might look using an Abstract Factory:
//: C10:AbstractFactory.cpp
// A gaming environment
#include <iostream>
using namespace std;
class Obstacle {
public:
virtual void action() = 0;
};