#include <CExtensibleFactory.h> template <class T> class CExtensibleFactory { public: void addCreator(std::string type, CCreator<T>* pCreator); T* create(std::string type); std::vector<std::string> getDescriptions(); }; #include <CCreator.h> template <class T> class CCreator { public: virtual T* operator()() = 0; virtual std::string describe() const = 0; };
A common pattern in object oriented programming
is the creation of a class hierarchy whose
ultimate base class is abstract and defines
a set of interface methods that concrete classes
must implement. For exmaple, in a graphics library,
the base class Shape
might
define an abstract method draw
which would then be implemented in
concrete classes like
Rectangle
or
Circle
.
Sometimes it's useful to be able to create an appropriate instance of a subclass of the ultimate base class of one of those hierarchies given a description or name of the class. Classes that can do that are called factory classes. If the class hierarchy is extensible by user code, it's important that the factory also be extensible.
The CExtensibleFactory
template class provides the machinery to do all of this.
To use it, you must specialize the factory to the
type of object it will return, and provide
and register Creator
objects that recognize type strings and
return the appropriate object.
Each extensible factory has a set of creators. Each creator is associated with a string. When the factory is asked to create an object it's given a string and that string is used to locate a creator which actually creates the desired object.
CCreator
is an abstract
base class for these object creators. Concrete
creators must implement the following methods
virtual = 0 T* operator()();
Returns a pointer new object of the concrete type associated with the creator.
virtual const = 0 std::string describe();
Returns a string that describes the object being made. If the factory is associated with some creational command in a larger program, this can be used to construct a help string that reflects the set of actual object types that can be created.
void addCreator(std::string type, CCreator<T>* pCreator);
Provides the factory a new creator;
pCreator
that's
associated with the string
type
. If a creator
for that type already exists it is silently
replaced. If the old creator was
dynamically created, this replacement
causes a memory leak.
T* create(std::string type);
Asks the factory to create a type using
the creator that was associated with
the type
string.
If no creator has been registered for this
type, nullptr is
returned.
std::vector<string> getDescription();
Returns a vector of all the creator descriptions.