Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Flyweight pattern
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
=== C++ === The C++ [[Standard Template Library]] provides several containers that allow unique objects to be mapped to a key. The use of containers helps further reduce memory usage by removing the need for temporary objects to be created. <syntaxhighlight lang="c++">#include <iostream> #include <map> #include <string> // Instances of Tenant will be the Flyweights class Tenant { public: Tenant(const std::string& name = "") : m_name(name) {} std::string name() const { return m_name; } private: std::string m_name; }; // Registry acts as a factory and cache for Tenant flyweight objects class Registry { public: Registry() : tenants() {} Tenant& findByName(const std::string& name) { if (!tenants.contains(name)) { tenants[name] = Tenant{name}; } return tenants[name]; } private: std::map<std::string, Tenant> tenants; }; // Apartment maps a unique tenant to their room number. class Apartment { public: Apartment() : m_occupants(), m_registry() {} void addOccupant(const std::string& name, int room) { m_occupants[room] = &m_registry.findByName(name); } void tenants() { for (const auto &i : m_occupants) { const int& room = i.first; const auto& tenant = i.second; std::cout << tenant->name() << " occupies room " << room << std::endl; } } private: std::map<int, Tenant*> m_occupants; Registry m_registry; }; int main() { Apartment apartment; apartment.addOccupant("David", 1); apartment.addOccupant("Sarah", 3); apartment.addOccupant("George", 2); apartment.addOccupant("Sarah", 12); apartment.addOccupant("Michael", 10); apartment.tenants(); return 0; } </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)