享元模式(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_map<std::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;
}
运行结果:文章来源:https://www.uudwc.com/A/ZGDqJ/
Concrete Flyweight: state1
Concrete Flyweight: state2
Concrete Flyweight: state2
在上述示例中,Flyweight是抽象享元类,定义了享元对象的接口。ConcreteFlyweight是具体享元类,实现了具体的享元对象。FlyweightFactory是享元工厂类,负责创建和管理享元对象。
在main()函数中,首先创建了一个享元工厂对象flyweightFactory。然后通过调用getFlyweight()方法来获取享元对象。如果工厂中不存在对应的享元对象,则创建一个新的享元对象并将其存储在工厂中;如果已存在对应的享元对象,则直接返回该对象。最后,通过调用享元对象的operation()方法来执行操作。
通过享元模式,可以减少对象的数量,节省内存空间。相同的数据可以被多个对象共享,从而降低了系统的开销。享元模式适用于需要创建大量相似对象的场景,可以提高系统的性能和效率。文章来源地址https://www.uudwc.com/A/ZGDqJ/