亨元模式通常可以用在大量重复、相似对象的场景,希望能够以最小的空间存储他们。
存储重复数据
通过map表的形式记录姓名的索引
#include<vector>
#include<string>
#include<map>
using namespace std;
typedef uint16_t key;
struct User {
User(const string& firstname, const string& secondname)
:first{ add(firstname) }, second{ add(secondname) } {}
protected:
key first, second;
static map<string, key> mp;
static key seed;
static key add(const string& s) {
if (mp.find(s) != mp.end()) {
return mp[s];
}
else {
mp[s] = seed++;
return seed-1;
}
}
};
减少内存损失
通过亨元模式,可以将字符串数据的修改记录下来,减少存储浪费的空间?
#include<vector>
#include<string>
#include<map>
#include<iostream>
using namespace std;
class BetterFormattedText {
public:
BetterFormattedText(string a):plain_text {a}{}
struct TextRange {
int start, end;
bool capitalize = false; //存储是否大写
bool covers(int position) const {
return position >= start && position <= end;
}
};
TextRange& get_range(int start, int end) {
formatting.emplace_back(TextRange{ start, end });
return *formatting.rbegin();
}
friend ostream& operator<<(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) { //遍历所有,若没有则设置为0
if (rng.covers(i) && rng.capitalize)
{
c = toupper(c);
break;
}
}
s += c;
}
return os << s;
}
private:
string plain_text;
vector<TextRange> formatting;
};
int main()
{
BetterFormattedText bft("This is a brave new world");
bft.get_range(10, 15).capitalize = true;
bft.get_range(3, 5).capitalize = true;
cout << bft;
return 0;
}
总结
亨元模式本质是一种节约内存空间的技术,具体形式是多样化的,可能是API、也可能是隐式的在幕后