《享元模式(极简c++)》

        本文章属于专栏- 概述 - 《设计模式(极简c++版)》-CSDN博客

模式说明
  • 方案:享元模式是一种结构型设计模式,旨在通过共享尽可能多的对象来最小化内存使用和提高性能。
    • 优点
      • 减少内存占用:通过共享相似对象的状态,减少了对象的数量,从而减少了内存消耗。
      • 提高性能:由于减少了对象的数量,降低了系统的负担,提高了系统的性能。
    • 缺点
      • 复杂性增加:实现享元模式可能需要引入额外的复杂性,例如维护共享对象的状态等。

本质思想:将对象分为可共享的内部状态和不可变的外部状态,通过共享内部状态来减少对象的数量,以节省内存和提高性能。

实践建议:在有大量相似对象时,且相似部分状态不变时使用(如果要变。则需要对象提供的接口全部线程安全,则有性能风险,需要慎重)

代码示例

#include <iostream>
#include <string>
#include <unordered_map>

// 抽象享元类
class Bird {
public:
    virtual void fly() const = 0;
};

// 具体享元类
class ConcreteBird : public Bird {
private:
    std::string type_;
public:
    ConcreteBird(const std::string& type) : type_(type) {}
    void fly() const override {
        std::cout << "A " << type_ << " is flying!" << std::endl;
    }
};

// 享元工厂类
class FlyweightFactory {
private:
    std::unordered_map<std::string, const Bird*> birds;
public:
    const Bird* getBird(const std::string& type) {
        auto it = birds.find(type);
        if (it == birds.end()) {
            // 如果不存在该类型的鸟,创建新的鸟对象
            birds[type] = new ConcreteBird(type);
            return birds[type];
        }
        return it->second;
    }
    ~FlyweightFactory() {
        for (auto& pair : birds) {
            delete pair.second; // 释放内存
        }
        birds.clear();
    }
};

int main() {
    FlyweightFactory factory;
    const Bird* bird1 = factory.getBird("sparrow");
    const Bird* bird2 = factory.getBird("sparrow");

    bird1->fly(); // 输出:A sparrow is flying!
    bird2->fly(); // 输出:A sparrow is flying!

    // 之后可以把bird1和bird2传递给其他对象,实现共享
    
    return 0;
}

  • 19
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值