当前位置: 首页 > 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.jsqmd.com/news/1032623/

相关文章:

  • LM Studio+OpenClaw本地智能体实战:绕过API费用的完整工作流部署
  • vLLM生产级部署指南:高吞吐低延迟大模型推理引擎实战
  • 哈尔滨 5 家猫犬舍实测测评|冰城极寒气候购宠首选伴西西 - 同城宠物优选基地
  • Linux环境下SoapUI 3.0接口自动化测试实战指南
  • ZigBee价格簇API实战:智能能源设备动态定价与需求响应开发指南
  • 青岛配眼镜怎么避坑?三个常见误区与正确做法 - 配眼镜新资讯
  • 常州奥迪Q7无损音响升级!阿尔派+赫兹轻奢改装,解锁车载HiFi音质 - 音乐人生汽车音响
  • 【Android Performance】CPU核心查询与控制速查手册:从cluster结构到核心上下线的完整命令集合
  • 《人月神话》---人月神话与现实
  • 基于HFSS仿真与耦合馈电技术的新型圆极化微带天线设计
  • 国产大模型合规应用实战指南:从部署到Prompt工程
  • 上海买狗深度避雷测评!5 家繁育舍真实踩坑对比,新手别踩星期狗圈套 - 同城宠物优选基地
  • 佛山长途搬厂搬家公司推荐,机房服务器精密设备专业搬运指南 - 从来都是英雄出少年
  • 重庆配眼镜怎么避坑?三条准则避开常见雷区 - 配眼镜新资讯
  • 广州办公环境好的写字楼|2026年6月四大楼宇深度测评,从净高到配套全面拆解 - 资讯速览
  • 反索引引擎:在过度分类时代捍卫复杂性
  • 11,清理蓝图中的faceright
  • 消息队列与任务调度:异步工作流的可靠性工程
  • 浏览器渲染层文档获取方案:跨平台文档内容提取技术解析
  • Prometheus-联邦机制
  • 如何快速搭建免费音乐库:洛雪音乐开源音源完整配置指南
  • ARM Cortex-M开发环境搭建:从KSDK平台库构建到OpenSDA调试实战
  • B站缓存视频合并:从碎片到完整的魔法之旅
  • JN516x开发板USB通信配置:FTDI驱动安装与虚拟串口识别实战
  • 5分钟快速上手:CMLM-ZhongJing中医大语言模型完整使用指南
  • 2026年美国留学机构哪家服务好:五家优选品牌全解析 - 科技焦点
  • 6%AFFF/AR抗溶性水成膜消防泡沫液品牌排行榜:浙江金瑞恒高分子聚合物形成稳定膜 - 品牌速递
  • 2026年沈阳不锈钢正规供货商排行榜:专业材质与诚信服务值得信赖推荐 - 品牌发掘
  • 聚稿星产品测试邀请:一款面向内容创作者的多平台一键分发工具 - 心梦EGO
  • 乌鲁木齐 5 家猫犬舍实测测评|西北干燥温差大购宠首选伴西西 - 同城宠物优选基地