在很多应用中,可能会创建大量相似对象,例如在文字处理器中每个字符对象。在这些场景下,如果每个对象都存在,将会导致巨大的内存开销。那么如何在避免大量颗粒度对象问题的同时,让外部客户程序仍然能够透明的使用面向对象的方式来进行操作呢?享元模式的主要动机是通过共享相似对象来减少内存使用,提高系统性能,来解决此类问题。
享元模式适用于以下情况:
模式定义: 运用共享技术有效地支持大量细粒度的对象。–《设计模式》GoF
享元模式由以下几个主要角色组成:
以下是享元模式的UML图:
下面我们通过C++代码示例来实现享元模式。
class Flyweight {
public:
virtual void operation(int extrinsicState) = 0;
virtual ~Flyweight() = default;
};
#include <iostream>
class ConcreteFlyweight : public Flyweight {
private:
int intrinsicState;
public:
ConcreteFlyweight(int state) : intrinsicState(state) {}
void operation(int extrinsicState) override {
std::cout << "Intrinsic State: " << intrinsicState
<< ", Extrinsic State: " << extrinsicState << std::endl;
}
};
#include <unordered_map>
#include <memory>
class FlyweightFactory {
private:
std::unordered_map<int, std::shared_ptr<Flyweight>> flyweights;
public:
std::shared_ptr<Flyweight> getFlyweight(int key) {
if (flyweights.find(key) == flyweights.end()) {
flyweights[key] = std::make_shared<ConcreteFlyweight>(key);
}
return flyweights[key];
}
};
int main() {
FlyweightFactory factory;
std::shared_ptr<Flyweight> fw1 = factory.getFlyweight(1);
std::shared_ptr<Flyweight> fw2 = factory.getFlyweight(2);
std::shared_ptr<Flyweight> fw3 = factory.getFlyweight(1); // Reuses the existing Flyweight
fw1->operation(10);
fw2->operation(20);
fw3->operation(30);
return 0;
}
享元模式在以下场景中非常有用:
std::mutex
)或者其他同步机制确保线程安全。因篇幅问题不能全部显示,请点此查看更多更全内容
Copyright © 2019- hzar.cn 版权所有 赣ICP备2024042791号-5
违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com
本站由北京市万商天勤律师事务所王兴未律师提供法律服务