Modern C++ Design Pattern/Chapter 11. 플라이웨이트

created : 2020-04-11T14:28:27+00:00
modified : 2020-09-26T14:21:47+00:00
cpp design pattern flyweight

static key add(const string& s) { auto it = names.right.find(s); if (it == names.right.end()) { names.insert({++seed, s}); return seed; } return it->second; }

const string& get_first_name() const { return names.left.find(last_name)->second; }

const string& get_last_name9) const { return names.left.find(last_name)->second; }


## `Boost.Flyweight`
```cpp
class BetterFormattedText
{
public:
  struct TextRange
  {
    int start, end;
    bool capitalize;

    bool covers(int position) const
    {
      return position >= start && position <= end;
    }
  };

private:
  string plain_text;
  vector<TextRange> formatting;
}

TextRange& get_range(int start, int end)
{
  formatting.emplace_back(TextRange{ start, end });
  return *formatting.rbegin();
}

friend std::ostream& operator<<(std::ostream& os,
  const BetterFormattedText& obj)
{
  string s;
  for (size_t i = 0; i < obj.plain_text.length(); i++)
  {
    auto c = obj.plain_text[i];
    for (const auto& rng : obj.formatting)
    {
      if (rng.covers(i) && rng.capitalize)
        c = toupper(c);
      s += c;
    }
  }
  return os << s;
}

요약