There are two design patterns that could be of help: Factory
and FlyWeight
.
Typically, your SWC_Label
class does not need to own a BMFont
, it only needs to manipulate one; my advice would be to use a Factory
of fonts, that will internally keep a handle on the fonts it knows about.
Simple example:
class FontFactory {
public:
typedef std::shared_ptr<BMFont> SharedFontPtr;
SharedFontPtr getFont(std::string const& name) const;
private:
std::map<std::string, SharedFontPtr> _fonts;
}; // class FontFactory
And then, the SWC_Label
class holds a std::shared_ptr<BMFont>
(relatively lightweight handle) rather than a full font class.
There are many variations on the topic:
- lazy load of yet unknown fonts (from the
Factory
) - keeping a
std::weak_ptr
reference in theFactory
, to reduce memory footprint as much as possible - not keeping a reference at all (potentially wasteful though), as you may end up with several copies in memory
To optimize memory consumptions of objects with a big common shared part but a small endemic part you might want to read on FlyWeight
, the case we have here being a degenerate case where there is no endemic part and thus you do not have to split the object in common/endemic parcels.