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