asked on
1) Virtual Base class with one pure virtual function:
class Acc {
virtual uint32_t common_method(uint32_t arg1, uint32_t arg2) = 0;
};
2) There are 8 different classes derived from this Base class "Acc" and
each of them has its own implementation of common_method(arg1, arg2);
class Acc_Der_1 : public Acc;
class Acc_Der_2 : public Acc;
.........................
.........................
class Acc_Der_8 : public Acc;
3) One Factory class that returns an object of one of the above 8 classes
based on some condition check.
class Acc_factory {
Acc* create_obj(uint32_t type) {
if (cond_1)
return new Acc_Der_1();
if (cond_2)
return new Acc_Der_2();
........................ /// so on .....
if (cond_8)
return new Acc_Der_8();
}
}
4) Finally a manage class which invokes the actual virtual method.
class Acc_Manager {
void main_func(uint32_t type) {
std::auto_ptr<Acc*> acc_obj (Acc_factory::get_instance->create_obj(type))
acc_obj->common_method(some_arg1, some_arg2);
}
};
typedef Acc* (*create_derived_acc)();
class Acc_factory {
static std::map<std::string, create_derived_acc> factory;
public:
static Acc* create_obj(const std::string & classname)
{
std::map<std::string, create_derived_acc>::iterator f;
if ((f = factory.find(classname)) == factory.end())
{
// class is not registered
return NULL;
}
create_derived_acc func = f->second;
Acc* pacc = func();
return pacc;
}
static add_create_func(const std::string & cn, create_derived_acc f)
{
factory[cn] = f;
}
};
// acc_der_9.h
...
class Acc_Der_9 : public Acc
{
static bool added_to_factory;
...
public:
static Acc* create() { return new Acc_Der_9(); }
...
// acc_der_9.cpp
...
#include "acc_der_9.h"
bool Acc_Der_9::added_to_factory = Acc::add_create_func("Acc_Der_9", Acc_Der_9::create);
...
C++ is an intermediate-level general-purpose programming language, not to be confused with C or C#. It was developed as a set of extensions to the C programming language to improve type-safety and add support for automatic resource management, object-orientation, generic programming, and exception handling, among other features.
TRUSTED BY
ASKER