设计模式:享元模式(C++实现)

享元模式(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;
}

运行结果:

Concrete Flyweight: state1
Concrete Flyweight: state2
Concrete Flyweight: state2

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

原文地址:https://blog.csdn.net/wydxry/article/details/133067584

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请联系站长进行投诉反馈,一经查实,立即删除!

h
上一篇 2023年09月26日 16:00
下一篇 2023年09月26日 16:03