StructuralC++verifiedVerified

Flyweight Pattern in C++

Minimizes memory usage by sharing fine-grained objects that represent repeated data, storing intrinsic state once and passing extrinsic state at call time.

How to Implement the Flyweight Pattern in C++

1Step 1: Flyweight stores shared intrinsic state

class CharacterStyle {
    std::string font_;
    int size_;
    std::string color_;
public:
    CharacterStyle(std::string font, int size, std::string color)
        : font_(std::move(font)), size_(size), color_(std::move(color)) {}

    void render(char c, int x, int y) const {
        std::cout << "'" << c << "' at (" << x << "," << y
                  << ") font=" << font_ << " size=" << size_
                  << " color=" << color_ << "\n";
    }
};

2Step 2: Factory ensures shared instances

class StyleFactory {
    std::map<std::string, std::shared_ptr<CharacterStyle>> cache_;
public:
    std::shared_ptr<CharacterStyle> getStyle(const std::string& font,
                                              int size,
                                              const std::string& color) {
        auto key = font + ":" + std::to_string(size) + ":" + color;
        auto it = cache_.find(key);
        if (it != cache_.end()) return it->second;

        auto style = std::make_shared<CharacterStyle>(font, size, color);
        cache_[key] = style;
        return style;
    }

    size_t uniqueStyles() const { return cache_.size(); }
};

int main() {
    StyleFactory factory;
    auto bold = factory.getStyle("Arial", 12, "black");
    auto same = factory.getStyle("Arial", 12, "black"); // reuses existing

    bold->render('H', 0, 0);
    same->render('i', 10, 0);

    std::cout << "Unique styles: " << factory.uniqueStyles() << "\n";
    std::cout << "Same instance: " << (bold.get() == same.get() ? "yes" : "no") << "\n";
}

Flyweight Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Flyweight Pattern in the Real World

A book publisher doesn’t print a separate metal typeface block for every letter ‘e’ on every page. Instead, one block for ‘e’ (intrinsic state) is reused in every position, with the printer supplying the ink color and position (extrinsic state) each time it is stamped. Thousands of impressions share one piece of metal.