38 lines
989 B
C++
38 lines
989 B
C++
/**
|
|
* @name 享元模式
|
|
* @brief: 高效共享大量细粒度对象
|
|
* @note 场景:文本编辑器字符格式、游戏粒子系统
|
|
*/
|
|
|
|
class CharacterStyle {
|
|
public:
|
|
CharacterStyle(const std::string& font, int size, bool bold)
|
|
: font(font), size(size), bold(bold) {}
|
|
// 风格属性...
|
|
private:
|
|
std::string font;
|
|
int size;
|
|
bool bold;
|
|
};
|
|
|
|
class StyleFactory {
|
|
public:
|
|
CharacterStyle* getStyle(const std::string& font, int size, bool bold) {
|
|
std::string key = font + std::to_string(size) + (bold ? "b" : "");
|
|
if (styles.find(key) == styles.end()) {
|
|
styles[key] = new CharacterStyle(font, size, bold);
|
|
}
|
|
return styles[key];
|
|
}
|
|
private:
|
|
std::unordered_map<std::string, CharacterStyle*> styles;
|
|
};
|
|
|
|
class TextCharacter {
|
|
public:
|
|
TextCharacter(char c, CharacterStyle* style)
|
|
: character(c), style(style) {}
|
|
private:
|
|
char character;
|
|
CharacterStyle* style; // 共享的样式对象
|
|
}; |