gfactory
static_and_dynamic_example.cc
Go to the documentation of this file.
1 #include "gfactory.h"
2 #include "gfactory_options.h"
3 #include "ShapeFactory.h"
4 #include "Car.h"
5 
6 // managerA: loads known classes Triangle and Box from the base Shape, in ShapeFactory.h
7 // managerB: loads DLL that instantiate derived factories - we only know of the base class, in this case "Car"
8 
9 int main(int argc, char *argv[]) {
10 
11  auto gopts = new GOptions(argc, argv, gfactory::defineOptions());
12 
13  auto log = std::make_shared<GLogger>(gopts, PLUGIN_LOGGER);
14 
15  GManager managerAV(log, "exampleAV"); // no verbosity
16  managerAV.RegisterObjectFactory<Triangle>("triangle");
17  managerAV.RegisterObjectFactory<Box>("box1");
18  managerAV.RegisterObjectFactory<Box>("box2");
19 
20  // putting A factory in map
21  // notice we're putting the base class in the map so we can call its virtual methods
22  map<string, Shape *> fffv;
23  fffv["triangle"] = managerAV.CreateObject<Shape>("triangle");
24  fffv["box1"] = managerAV.CreateObject<Shape>("box1");
25  fffv["box2"] = managerAV.CreateObject<Shape>("box2");
26 
27  // aShape is same pointer as map element
28  Shape *aShape = fffv["triangle"];
29 
30  // calling base and derived methods
31  aShape->Area();
32  fffv["triangle"]->Area();
33  fffv["box1"]->Area();
34 
35  log->info(0, " Shape pointers from map: ", fffv["triangle"], ", from direct pointer:", aShape);
36 
37  // once we're done with it
38  managerAV.clearDLMap();
39 
40 
41  // B manages Cars. Notice, we do not need the derived class headers here!
42  // PRAGMA: These two names must match in registerDL and in LoadAndRegisterObjectFromLibrary:
43  // that's ok but need to spit error if that doesn't happen
44  GManager managerB(log, "exampleB");
45 
46  map<string, Car *> ggg;
47  ggg["tesla"] = managerB.LoadAndRegisterObjectFromLibrary<Car>("test_dyn_factory1");
48  ggg["ford"] = managerB.LoadAndRegisterObjectFromLibrary<Car>("test_dyn_factory2");
49  Car *aCar = ggg["ford"];
50 
51 
52  // calling base and derived method
53  ggg["tesla"]->go();
54  ggg["ford"]->go();
55 
56  log->info(0, " Car pointers from map: ", ggg["ford"], ", from direct pointer:", aCar);
57  log->info(0, " run generalCarVar method from factory map: ", ggg["tesla"]->generalCarVar);
58 
59  // clearing the map - this should be done in classes destructors
60  managerB.clearDLMap();
61 
62 }
Definition: Car.h:6
virtual void go()=0
Instantiates derived classes either statically or dynamically.
Definition: gfactory.h:42
void clearDLMap()
Definition: gfactory.h:158
Base * CreateObject(std::string name) const
Definition: gfactory.h:103
void RegisterObjectFactory(std::string name)
Definition: gfactory.h:87
T * LoadAndRegisterObjectFromLibrary(std::string name)
Definition: gfactory.h:124
virtual void Area()=0
constexpr const char * PLUGIN_LOGGER
GOptions defineOptions()
int main(int argc, char *argv[])