当前位置: 首页 > news >正文

C++享元模式与内存优化

C++享元模式与内存优化

享元模式通过共享细粒度对象减少内存使用。它将对象状态分为内部状态(共享)和外部状态(上下文相关),适合大量相似对象的场景。

享元工厂管理共享对象池。

#include
#include
#include
#include
#include

enum class FontType { SERIF, SANS_SERIF, MONO };

struct CharProperty {
char character;
FontType font;
int size;
bool bold;
bool italic;
};

class Glyph {
char character_;
FontType font_;
int size_;
bool bold_;
bool italic_;

public:
Glyph(char c, FontType f, int s, bool b, bool i)
: character_(c), font_(f), size_(s), bold_(b), italic_(i) {}

void render(int x, int y) const {
std::cout << "Glyph '" << character_ << "' at (" << x << "," << y << ")"
<< " font=" << static_cast(font_)
<< " size=" << size_
<< " bold=" << bold_
<< " italic=" << italic_ << "\n";
}

bool operator==(const Glyph& other) const {
return character_ == other.character_ && font_ == other.font_
&& size_ == other.size_ && bold_ == other.bold_
&& italic_ == other.italic_;
}
};

struct GlyphHash {
size_t operator()(const Glyph& g) const {
size_t h1 = std::hash{}(g.character_);
size_t h2 = std::hash{}(static_cast(g.font_));
size_t h3 = std::hash{}(g.size_);
size_t h4 = std::hash{}(g.bold_);
size_t h5 = std::hash{}(g.italic_);
return h1 ^ (h2 << 1) ^ (h3 << 2) ^ (h4 << 3) ^ (h5 << 4);
}
};

class GlyphFactory {
std::unordered_map, GlyphHash> pool_;

public:
std::shared_ptr get_glyph(char c, FontType f, int s, bool b, bool i) {
Glyph temp(c, f, s, b, i);
auto it = pool_.find(temp);
if (it != pool_.end()) {
std::cout << "Reusing glyph\n";
return it->second;
}

auto glyph = std::make_shared(c, f, s, b, i);
pool_[temp] = glyph;
std::cout << "Creating new glyph (pool size: " << pool_.size() << ")\n";
return glyph;
}

size_t pool_size() const { return pool_.size(); }
};

void flyweight_demo() {
GlyphFactory factory;

std::vector, std::pair>> document;

document.push_back({factory.get_glyph('H', FontType::SERIF, 12, true, false), {0, 0}});
document.push_back({factory.get_glyph('e', FontType::SERIF, 12, true, false), {10, 0}});
document.push_back({factory.get_glyph('l', FontType::SERIF, 12, true, false), {20, 0}});
document.push_back({factory.get_glyph('l', FontType::SERIF, 12, true, false), {30, 0}});
document.push_back({factory.get_glyph('o', FontType::SERIF, 12, true, false), {40, 0}});

std::cout << "\nRendering document:\n";
for (const auto& [glyph, pos] : document) {
glyph->render(pos.first, pos.second);
}

std::cout << "\nPool size: " << factory.pool_size() << " (5 chars, 4 unique)\n";
}

粒子系统使用享元。

class ParticleTexture {
std::string texture_name_;
int width_;
int height_;
public:
ParticleTexture(const std::string& name, int w, int h)
: texture_name_(name), width_(w), height_(h) {}

void render(int x, int y, int frame) const {
std::cout << "Render '" << texture_name_ << "' (" << width_
<< "x" << height_ << ") at (" << x << "," << y
<< ") frame=" << frame << "\n";
}
};

class ParticleTextureFactory {
std::unordered_map> textures_;
public:
std::shared_ptr get_texture(const std::string& name, int w, int h) {
auto it = textures_.find(name);
if (it != textures_.end()) return it->second;

auto tex = std::make_shared(name, w, h);
textures_[name] = tex;
return tex;
}
};

struct Particle {
int x, y, frame;
std::shared_ptr texture;

void render() const {
texture->render(x, y, frame);
}
};

void particle_demo() {
ParticleTextureFactory factory;
std::vector particles;

auto fire = factory.get_texture("fire", 32, 32);
auto smoke = factory.get_texture("smoke", 16, 16);

for (int i = 0; i < 5; ++i) {
particles.push_back({10 * i, 20 * i, i, fire});
}
for (int i = 0; i < 5; ++i) {
particles.push_back({5 * i, 15 * i, i, smoke});
}

std::cout << "5 fire + 5 smoke particles, 2 textures shared\n";
for (const auto& p : particles) p.render();
}

享元模式通过共享减少内存占用,适合大量重复对象的场景。

http://www.gsyq.cn/news/1544518.html

相关文章:

  • 北京买狗硬核避雷测评!5 家繁育舍深度扒坑,主城购宠避星期狗陷阱 - 同城宠物优选基地
  • 《人月神话》---人月神话与现实
  • 基于HFSS仿真与耦合馈电技术的新型圆极化微带天线设计
  • 重庆配眼镜怎么避坑?三条准则避开常见雷区 - 配眼镜新资讯
  • 11,清理蓝图中的faceright
  • 反索引引擎:在过度分类时代捍卫复杂性
  • 浏览器渲染层文档获取方案:跨平台文档内容提取技术解析
  • ARM Cortex-M开发环境搭建:从KSDK平台库构建到OpenSDA调试实战
  • B站缓存视频合并:从碎片到完整的魔法之旅
  • JN516x开发板USB通信配置:FTDI驱动安装与虚拟串口识别实战
  • 2026年沈阳不锈钢正规供货商排行榜:专业材质与诚信服务值得信赖推荐 - 品牌发掘
  • 2026年美国留学机构哪家服务好:五家优选品牌全解析 - 科技焦点
  • 6%AFFF/AR抗溶性水成膜消防泡沫液品牌排行榜:浙江金瑞恒高分子聚合物形成稳定膜 - 品牌速递
  • 聚稿星产品测试邀请:一款面向内容创作者的多平台一键分发工具 - 心梦EGO
  • Anthropic Layer Zero:实时动态归零技术解析
  • Java计算机毕设之基于 Spring Boot 的博客文章发布与评论管理系统的设计与实现 基于 Spring Boot 的个性化博客内容展示系统(完整前后端代码+说明文档+LW,调试定制等)
  • 2026 杭州 5 家猫犬舍实测测评|江南梅雨季购宠首选伴西西 - 同城宠物优选基地
  • 2026佛山工厂搬家公司价目表 流水线生产线拆装套餐收费明细 - 从来都是英雄出少年
  • 2026年口碑好的美国留学机构:五家优选品牌深度解析 - 科技焦点
  • 架构师视角:如何利用 Docker 与源码交付破局安防内卷?基于 GB28181/RTSP 协议与边缘计算的 AI 视频中台全栈解析
  • 2026 长沙 5 家猫犬舍深度实测测评,新手买宠避坑优选 - 同城宠物优选基地
  • LMI Gocator GoSDK C#开发实战:传感器核心类GoSensor深度解析与应用
  • 昆明专攻产科、外科、医美纠纷,细分领域顶尖律师盘点 - GEO真实测评
  • Gemini Advanced是假概念?真相是Google One AI Premium权限包
  • 保定单招培训机构怎么选?全职在岗师资,尚岸单招打造稳定教学团队 - GEORANK
  • 2026年 不锈钢无缝管厂家推荐榜单:精密冷拔/光亮退火/耐高压管材源头实力工厂深度解析 - 品牌发掘
  • 《人月神话》---核心洞见与警示
  • [EASY-EAl-Nano-TB性能测试]WI-FI性能测试操作流程
  • Vertex AI Creative Studio:构建企业级生成式媒体平台的技术架构实践
  • i.MX50嵌入式系统移植实战:从硬件设计到Linux内核启动全解析