哈尔滨 网站开发,笔记本做网站服务器,江苏住房和城乡建设信息网站,wordpress 自动封面享元模式是一种结构型设计模式#xff0c;旨在有效地支持大量细粒度的对象共享#xff0c;从而减少内存消耗和提高性能。
在享元模式中#xff0c;对象分为两种#xff1a;内部状态#xff08;Intrinsic State#xff09;和外部状态#xff08;Extrinsic State#xf…享元模式是一种结构型设计模式旨在有效地支持大量细粒度的对象共享从而减少内存消耗和提高性能。
在享元模式中对象分为两种内部状态Intrinsic State和外部状态Extrinsic State。内部状态是对象可以共享的状态它存储在享元对象内部并且不会随着外部环境的改变而改变外部状态是对象的外部环境可以变化的部分它由客户端传递给享元对象并且在享元对象之外维护。
享元模式的关键是使用共享对象来减少内存使用和提高性能。当需要创建新对象时首先检查是否已经存在具有相同内部状态的对象如果存在则返回该对象的引用如果不存在则创建一个新对象并将其加入到共享池中以便下次可以重复使用。
#include iostream
#include map
#include string// 抽象享元类
class Flyweight {
public:virtual ~Flyweight() {}virtual void operation(const std::string unique_state) const 0;
};// 具体享元类
class ConcreteFlyweight : public Flyweight {
public:ConcreteFlyweight(const std::string shared_state) : shared_state_(shared_state) {}void operation(const std::string unique_state) const override {std::cout ConcreteFlyweight: Shared state ( shared_state_ ), Unique state ( unique_state )\n;}private:std::string shared_state_;
};// 享元工厂类
class FlyweightFactory {
public:Flyweight* getFlyweight(const std::string shared_state) {if (flyweights_.find(shared_state) flyweights_.end()) {flyweights_[shared_state] new ConcreteFlyweight(shared_state);}return flyweights_[shared_state];}~FlyweightFactory() {for (auto it flyweights_.begin(); it ! flyweights_.end(); it) {delete it-second;}flyweights_.clear();}private:std::mapstd::string, Flyweight* flyweights_;
};int main() {FlyweightFactory factory;Flyweight* flyweight1 factory.getFlyweight(shared_state_1);flyweight1-operation(unique_state_1);Flyweight* flyweight2 factory.getFlyweight(shared_state_2);flyweight2-operation(unique_state_2);Flyweight* flyweight3 factory.getFlyweight(shared_state_1);flyweight3-operation(unique_state_3);return 0;
}/*
在这个示例中Flyweight 是抽象享元类定义了操作接口 operation()。
ConcreteFlyweight 是具体享元类实现了抽象享元类的接口。
FlyweightFactory 是享元工厂类负责创建和管理享元对象。在 main() 函数中我们使用享元工厂来获取享元对象并且重复使用了具有相同内部状态的对象。*/
觉得有帮助的话打赏一下呗。。