印度电商平台网站建设策划,外包兼职做图的网站,建立网站的链接结构有哪几种形式?,网站开发定制合同范本享元模式#xff08;Flyweight Pattern#xff09;是一种结构设计模式#xff0c;它通过共享对象来有效地支持大量细粒度的对象。享元模式的目标是尽量减少内存使用#xff0c;通过共享相同的数据来减少对象的数量。 以下是一个简单的C享元模式的示例#xff1a;
#includ…享元模式Flyweight Pattern是一种结构设计模式它通过共享对象来有效地支持大量细粒度的对象。享元模式的目标是尽量减少内存使用通过共享相同的数据来减少对象的数量。 以下是一个简单的C享元模式的示例
#include iostream
#include unordered_map// 抽象享元类
class Flyweight
{
public:virtual void operation() 0;
};// 具体享元类
class ConcreteFlyweight : public Flyweight
{
private:std::string intrinsicState;public:ConcreteFlyweight(const std::string intrinsicState) : intrinsicState(intrinsicState) {}void operation() override{std::cout Concrete Flyweight: intrinsicState std::endl;}
};// 享元工厂类
class FlyweightFactory
{
private:std::unordered_mapstd::string, Flyweight * flyweights;public:Flyweight *getFlyweight(const std::string intrinsicState){if (flyweights.find(intrinsicState) flyweights.end()){flyweights[intrinsicState] new ConcreteFlyweight(intrinsicState);}return flyweights[intrinsicState];}~FlyweightFactory(){for (auto it flyweights.begin(); it ! flyweights.end(); it){delete it-second;}flyweights.clear();}
};int main()
{FlyweightFactory flyweightFactory;Flyweight *flyweight1 flyweightFactory.getFlyweight(state1);Flyweight *flyweight2 flyweightFactory.getFlyweight(state2);Flyweight *flyweight3 flyweightFactory.getFlyweight(state2);flyweight1-operation();flyweight2-operation();flyweight3-operation();return 0;
}运行结果
Concrete Flyweight: state1
Concrete Flyweight: state2
Concrete Flyweight: state2在上述示例中Flyweight是抽象享元类定义了享元对象的接口。ConcreteFlyweight是具体享元类实现了具体的享元对象。FlyweightFactory是享元工厂类负责创建和管理享元对象。 在main()函数中首先创建了一个享元工厂对象flyweightFactory。然后通过调用getFlyweight()方法来获取享元对象。如果工厂中不存在对应的享元对象则创建一个新的享元对象并将其存储在工厂中如果已存在对应的享元对象则直接返回该对象。最后通过调用享元对象的operation()方法来执行操作。 通过享元模式可以减少对象的数量节省内存空间。相同的数据可以被多个对象共享从而降低了系统的开销。享元模式适用于需要创建大量相似对象的场景可以提高系统的性能和效率。