Under the hood¶
Registry classes¶
Registry classes statically hold instances of derived classes, and can be used to allocate a derived class dependent on some text string. The code thread below illustrates how the GModels::read() method extracts models from an XML file, allocates the requested model through the GModelRegistry::alloc() method, and appends the model to the model container.
C++
1int n = lib->elements("source"); // Get number of sources
2for (int i = 0; i < n; ++i) { // Loop over sources
3 const GXmlElement* src = lib->element("source", i); // Get pointer on source
4 std::string type = src->attribute("type"); // Get source model type
5 GModelRegistry registry; // Get model registry
6 GModel* ptr = registry.alloc(type); // Allocate model of specific type
7 if (ptr != NULL) { // If model is valid:
8 ptr->read(*src); // - read model
9 append(*ptr); // - append it to container
10 delete ptr; // - free model
11 }
12}
To access the registry information it is sufficient to create an instance of
the registry. To illustrate how the registry is filled the
src/model/GModelSky.cpp
file can be examined:
C++
1const GModelSky g_pointsource_seed("PointSource");
2const GModelSky g_extendedsource_seed("ExtendedSource");
3const GModelSky g_diffusesource_seed("DiffuseSource");
4const GModelSky g_compositesource_seed("CompositeSource");
5const GModelRegistry g_pointsource_registry(&g_pointsource_seed);
6const GModelRegistry g_extendedsource_registry(&g_extendedsource_seed);
7const GModelRegistry g_diffusesource_registry(&g_diffusesource_seed);
8const GModelRegistry g_compositesource_registry(&g_compositesource_seed);
Here four instances of GModelSky are created as global variables which are appended to the GModelRegistry registry by creating an instance of the registry which takes the address of the GModelSky instance as argument.
Registries are widely used throughout GammaLib for the handling of models and its components, and the handling of the observations of the different supported instruments.