C++设计模式——Flyweight享元模式

一,享元模式简介

享元模式是一种结构型设计模式,它将每个对象中各自保存一份数据的方式改为多个对象共享同一份数据,该模式可以有效减少应用程序的内存占用。
享元模式的核心思想是共享和复用,通过设置共享资源来避免创建过多的实例。
当应用程序的内部包含大量的对象,且对象之间包含相似的数据或状态时,可以使用享元模式来共享这些数据或状态。
享元模式的内部涉及到工厂模式的使用,因为它需要创建一个享元工厂来管理共享资源池。这个共享资源池,又称为享元池(Flyweight Pool),这里面包含多个访问共享数据的享元对象。当客户端需要使用一个享元对象时,享元工厂会从池中获取一个已有的享元对象,如果对象不存在,则创建一个新的享元对象。

二,享元模式的结构

1.内部状态(Intrinsic State):对象之间容易重复的、可以共享的、且变动很少的成员变量,该变量在享元模式中被共享。
2.外部状态(Extrinsic State):对象之间各不相同的、不能共享的、且随着不同场景而变化的成员变量,该变量被调用的客户端所设置和更改。
3.享元工厂类(Flyweight Factory):替外部客户端管理共享资源的类。
4.抽象享元类(Flyweight):享元模式的核心,由享元工厂进行创建和管理,里面包含了内部状态,但不包含外部状态。
5.共享的具体享元类(Concrete Flyweight):实现了Flyweight声明的接口并访问和存储了内部状态。
对应UML类图:

代码实现:

#include <iostream>
#include <memory>
#include<unordered_map>

using namespace std;

class Flyweight {
protected:
    int id; //内部状态

public:
    Flyweight(int id) : id(id) {}


    virtual void operation() const = 0;
};

class ConcreteFlyweightA : public Flyweight {
public:
    ConcreteFlyweightA() : Flyweight(1) {}
    void operation() const override {
        cout << "Concrete Flyweight A, id: " << id << endl;
    }
};

class ConcreteFlyweightB : public Flyweight {
public:
    ConcreteFlyweightB() : Flyweight(2) {}
    void operation() const override {
        cout << "Concrete Flyweight B, id: " << id << endl;
    }
};

// 定义享元工厂
class FlyweightFactory {
private:
    std::unordered_map<int, shared_ptr<Flyweight>> flyweights;

public:
    FlyweightFactory() {}

    //返回享元对象
    std::shared_ptr<Flyweight> getConcreteFlyweight(int id) {
        if (flyweights.find(id) == flyweights.end()) {
            if (id % 2 == 0) {
                flyweights[id] = make_shared<ConcreteFlyweightA>();
            }
            else {
                flyweights[id] = make_shared<ConcreteFlyweightB>();
            }
        }
        return flyweights[id];
    }
};

int main() {
    FlyweightFactory factory;
    shared_ptr<Flyweight> f1 = factory.getConcreteFlyweight(1);
    shared_ptr<Flyweight> f2 = factory.getConcreteFlyweight(2);
    shared_ptr<Flyweight> f3 = factory.getConcreteFlyweight(3);

    f1->operation();
    f2->operation();
    f3->operation();

    return 0;
}

运行结果:

Concrete Flyweight B, id: 2
Concrete Flyweight A, id: 1
Concrete Flyweight B, id: 2

三,享元模式的工作步骤

1.拆分类的成员变量,将成员变量拆分成以下两种:不变的、可能在对象之间重复使用的。变化的、随着应用场景而改动的。
2.将不变的,可重复的成员变量的属性设置为不可修改,并在构造函数中赋初始值。
3.创建享元类,并将共享的成员变量集成到享元类。
4.创建享元工厂类来管理共享的资源池,客户端与享元对象的交互借助享元工厂来实现。
5.优化共享资源池的代码实现,这可能涉及到事件驱动、回调函数或者策略模式的应用。

四,享元模式的应用场景

图形或图像处理:在大型游戏或图形编辑器开发中,同一个形状(如矩形)或颜色等状态会重复出现很多次,基于享元模式可以降低内存开销。
数据库处理优化:数据库被频繁地连接和请求时,享元模式可以管理这些连接并复用它们,提高处理的性能。
UI组件开发:在用户界面中,当创建多个界面窗口时,像按钮、图标等小部件会在创建界面窗口时有大量重复,使用享元模式可以减少界面之间重复组件的数量,提高性能。

五,享元模式的优缺点

享元模式的优点:
1.增加了系统资源的可重用性,节省了系统资源。
2.基于共享的结构,降低了内存消耗。
3.系统可扩展性强,新增对象时可直接复用共享资源。
4.降低了对象内部的结构复杂性。
享元模式的缺点:
1.使代码结构更加复杂。
2.当需要被共享的资源量级很小时,该模式的性能提升并不显著。
3.将共享变量放在构造函数中进行赋值,额外增加了初始化的时间。
4.引入了"共享"这种结构,会导致潜在的线程安全问题。
5.编写代码需要考虑保证状态的同步和一致性问题,否则会导致bug的产生。

六,代码实战

Demo:模拟字符编辑器
#include <iostream>
#include <map>

using namespace std;

//Flyweight
class Character {
public:
    Character(char symbol) : symbol_(symbol) {}
    Character() = default;

    void print() const {
        cout << "Character: " << symbol_ << endl;
    }

private:
    char symbol_;
};

//Flyweight factory
class CharacterFactory {
public:
    static const Character& getCharacter(char symbol) {
        if (characters_.find(symbol) == characters_.end()) {
            characters_[symbol] = Character(symbol);
            cout << "Create new char." << endl;
        }
        return characters_[symbol];
    }

private:
    static map<char, Character> characters_;
};

map<char, Character> CharacterFactory::characters_;

int main() {
    const Character& A = CharacterFactory::getCharacter('A');
    const Character& B = CharacterFactory::getCharacter('B');

    //Reusing 'A'
    const Character& A2 = CharacterFactory::getCharacter('A');

    A.print();
    B.print();
    A2.print();

    return 0;
}

运行结果:

Create new char.
Create new char.
Character: A
Character: B
Character: A

七,参考阅读

https://softwarepatterns.com/cpp/flyweight-software-pattern-cpp-example
https://www.pentalog.com/blog/design-patterns/flyweight-design-patterns/
https://design-patterns.readthedocs.io/zh-cn/latest/structural_patterns/flyweight.html
  • 17
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值