Boost logo

Boost :

From: Rob & Lori (Rob.Lori_at_[hidden])
Date: 2003-08-28 17:27:06


For those of you who are unfamiliar with pluggable factories, I suggest
reading the following C++ Report article:
http://www.adtmag.com/joop/crarticle.asp?ID=1520

To give a brief description, pluggable factories allow programmers to
create instances of a class by just referencing a class identifier.
Pluggable factories are extremely helpful anytime you wish to construct
a class based on outside input such as reconstructing classes sent over
a TCP/IP stream, constructing classes read from a file, constructing
classes to execute commands read in from a scripting/macro language, etc.

The pluggable factory has these features:
1. Classes can be registered and unregistered dynamically
2. Any data type that implements the assignment and comparison operators
can be used as a class identifier type
3. Classes can be registered with multiple class identifier's, even if
they are of different data types
3. Instances of new classes can be created simply by passing the correct
class identifier
4. The class identifier value can be retrieved for any given registered
class

Let me know what you guys think.

Rob Geiman

Example usage:

typedef ObjectFactory<Command> CommandFactory;

static std::string open_file_command = "open_file";
static std::string close_file_command = "close_file";
static std::string find_text_command = "find_text";

...

CommandFactory::Register<OpenFileCommand>(open_file_command);
CommandFactory::Register<CloseFileCommand>(close_file_command);
CommandFactory::Register<FindTextCommand>(find_text_command);

...

// Loop through macro stream, reading in and executing all commands
std::string cmd_text;

while (macro_stream.good() && !macro_stream.eof())
{
    macro_stream >> cmd_text;

    Command *cmd = CommandFactory::Create(cmd_text);

    if (cmd)
    {
        cmd->ExtractParams(macro_stream);
        cmd->Execute();
    }
    else
    {
        std::cout << "Unknown command: " << cmd_text << std::endl;
    }
}

...

std::cout << "Class OpenFileCommand registered with id " <<
CommandFactory::GetClassId<OpenFileCommand, string>() << std::endl;
std::cout << "Class CloseFileCommand registered with id " <<
CommandFactory::GetClassId<OpenFileCommand, string>() << std::endl;
std::cout << "Class FindTextCommand registered with id " <<
CommandFactory::GetClassId<OpenFileCommand, string>() << std::endl;

...

CommandFactory::Unregister(open_file_command);
CommandFactory::Unregister(close_file_command);
CommandFactory::Unregister(find_text_command);


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk