C++中的享元模式

目录

[享元模式(Flyweight Pattern)](#享元模式(Flyweight Pattern))

实际应用

文字编辑器中的字符

修仙游戏中的地图瓦片

图形编辑器中的图形对象

总结


享元模式(Flyweight Pattern)

享元模式是一种结构型设计模式,用于减少对象的内存使用和提高性能。该模式通过共享相似对象之间的公共部分来最小化内存使用。这些公共部分称为享元(Flyweight),而不同的部分称为非共享部分。

实际应用

文字编辑器中的字符

假设正在开发一个文字编辑器,这就可以使用享元模式来共享文本中重复出现的字符,减少内存使用。

cpp 复制代码
#include <iostream>
#include <unordered_map>
#include <memory>

// 享元类:字符
class Character {
private:
    char symbol;
    // 非共享状态可以作为外部状态
    int fontSize;
public:
    Character(char symbol, int fontSize) : symbol(symbol), fontSize(fontSize) {}

    void display(int position) const {
        std::cout << "Character '" << symbol << "' displayed at position " << position
                  << " with font size " << fontSize << "\n";
    }
};

// 享元工厂类
class CharacterFactory {
private:
    std::unordered_map<char, std::shared_ptr<Character>> characters;
public:
    std::shared_ptr<Character> getCharacter(char symbol, int fontSize) {
        if (characters.find(symbol) == characters.end()) {
            characters[symbol] = std::make_shared<Character>(symbol, fontSize);
        }
        return characters[symbol];
    }
};

int main() {
    CharacterFactory characterFactory;
    // 使用享元工厂创建并共享字符
    auto char1 = characterFactory.getCharacter('A', 12);
    auto char2 = characterFactory.getCharacter('B', 12);
    auto char3 = characterFactory.getCharacter('A', 14);
    auto char4 = characterFactory.getCharacter('B', 12);

    char1->display(1);
    char2->display(2);
    char3->display(3);
    char4->display(4);

    return 0;
}

修仙游戏中的地图瓦片

假设游戏中有许多地图瓦片,这就可以使用享元模式来共享相同类型的地图瓦片。

cpp 复制代码
#include <iostream>
#include <unordered_map>
#include <memory>

// 享元类:地图瓦片
class MapTile {
private:
    int type;
    // 非共享状态可以作为外部状态
    int x, y;
public:
    MapTile(int type, int x, int y) : type(type), x(x), y(y) {}

    void draw() const {
        std::cout << "Drawing map tile of type " << type << " at position (" << x << ", " << y << ")\n";
    }
};

// 享元工厂类
class MapTileFactory {
private:
    std::unordered_map<int, std::shared_ptr<MapTile>> mapTiles;
public:
    std::shared_ptr<MapTile> getMapTile(int type, int x, int y) {
        int key = type * 10000 + x * 100 + y;
        if (mapTiles.find(key) == mapTiles.end()) {
            mapTiles[key] = std::make_shared<MapTile>(type, x, y);
        }
        return mapTiles[key];
    }
};

int main() {
    MapTileFactory mapTileFactory;
    // 使用享元工厂创建并共享地图瓦片
    auto tile1 = mapTileFactory.getMapTile(1, 0, 0);
    auto tile2 = mapTileFactory.getMapTile(2, 1, 0);
    auto tile3 = mapTileFactory.getMapTile(1, 0, 0);
    auto tile4 = mapTileFactory.getMapTile(2, 1, 0);

    tile1->draw();
    tile2->draw();
    tile3->draw();
    tile4->draw();

    return 0;
}

图形编辑器中的图形对象

假设正在开发一个图形编辑器,编辑器中有许多图形对象。这时候就可以使用享元模式来共享相同类型的图形对象。

cpp 复制代码
#include <iostream>
#include <unordered_map>
#include <memory>

// 享元类:图形对象
class Shape {
protected:
    std::string type;
    // 非共享状态可以作为外部状态
    int x, y;
public:
    Shape(const std::string& type, int x, int y) : type(type), x(x), y(y) {}

    virtual void draw() const = 0;
};

// 具体享元类:圆形
class Circle : public Shape {
public:
    Circle(int x, int y) : Shape("Circle", x, y) {}

    void draw() const override {
        std::cout << "Drawing " << type << " at position (" << x << ", " << y << ")\n";
    }
};

// 享元工厂类
class ShapeFactory {
private:
    std::unordered_map<std::string, std::shared_ptr<Shape>> shapes;
public:
    std::shared_ptr<Shape> getShape(const std::string& type, int x, int y) {
        if (shapes.find(type) == shapes.end()) {
            if (type == "Circle") {
                shapes[type] = std::make_shared<Circle>(x, y);
            } // 可以添加更多类型的图形对象
        }
        return shapes[type];
    }
};

int main() {
    ShapeFactory shapeFactory;
    // 使用享元工厂创建并共享图形对象
    auto circle1 = shapeFactory.getShape("Circle", 0, 0);
    auto circle2 = shapeFactory.getShape("Circle", 1, 1);
    auto circle3 = shapeFactory.getShape("Circle", 0, 0);
    auto circle4 = shapeFactory.getShape("Circle", 1, 1);

    circle1->draw();
    circle2->draw();
    circle3->draw();
    circle4->draw();

    return 0;
}

总结

享元模式可以在减少内存使用和提高性能方面发挥作用,因为享元模式可以有效地共享相似对象之间的公共部分,从而减少内存占用。

相关推荐
m0_748245348 分钟前
python——Django 框架
开发语言·python·django
曼巴UE513 分钟前
UE5.3 C++ TArray系列(一)
开发语言·c++·ue5
熬夜苦读学习24 分钟前
Linux文件系统
linux·运维·服务器·开发语言·后端
菜鸟一枚在这32 分钟前
深度解析建造者模式:复杂对象构建的优雅之道
java·开发语言·算法
阿巴~阿巴~1 小时前
多源 BFS 算法详解:从原理到实现,高效解决多源最短路问题
开发语言·数据结构·c++·算法·宽度优先
CoderCodingNo2 小时前
【GESP】C++二级真题 luogu-b3924, [GESP202312 二级] 小杨的H字矩阵
java·c++·矩阵
奔跑吧邓邓子2 小时前
【Python爬虫(34)】Python多进程编程:开启高效并行世界的钥匙
开发语言·爬虫·python·多进程
刃神太酷啦3 小时前
堆和priority_queue
数据结构·c++·蓝桥杯c++组
Heris993 小时前
2.22 c++练习【operator运算符重载、封装消息队列、封装信号灯集】
开发语言·c++
----云烟----3 小时前
C/C++ 中 volatile 关键字详解
c语言·开发语言·c++