设计模式11之c++享元模式(含示例代码)

享元模式(Flyweight Pattern)是一种结构型设计模式,它通过共享对象来减少内存使用和提高性能。它通常用于需要大量创建相似对象的场景,比如字符、图形等。


#include <iostream>
#include <unordered_map>
// 共享对象的抽象基类
class Flyweight {
    
    
public:
    virtual void operation() = 0;
};
// 具体共享对象
class ConcreteFlyweight : public Flyweight {
    
    
public:
    ConcreteFlyweight(char state) : state_(state) {
    
    }
    void operation() override {
    
    
        std::cout << "ConcreteFlyweight with state " << state_ << std::endl;
    }
private:
    char state_;
};
// 享元工厂
class FlyweightFactory {
    
    
public:
    Flyweight* getFlyweight(char state) {
    
    
        auto it = flyweights_.find(state);
        if (it != flyweights_.end()) {
    
    
            std::cout << "Using existing flyweight with state " << state << std::endl;
            return it->second;
        }
        else {
    
    
            std::cout << "Creating new flyweight with state " << state << std::endl;
            Flyweight* flyweight = new ConcreteFlyweight(state);
            flyweights_[state] = flyweight;
            return flyweight;
        }
    }
    ~FlyweightFactory() {
    
    
        for (auto it = flyweights_.begin(); it != flyweights_.end(); ++it) {
    
    
            delete it->second;
        }
    }
private:
    std::unordered_map<char, Flyweight*> flyweights_;
};
int main() {
    
    
    FlyweightFactory factory;
    // 创建并使用共享对象
    Flyweight* f1 = factory.getFlyweight('a');
    f1->operation();
    // 再次使用已有的共享对象
    Flyweight* f2 = factory.getFlyweight('a');
    f2->operation();
    // 创建一个新的共享对象
    Flyweight* f3 = factory.getFlyweight('b');
    f3->operation();
    return 0;
}

在这个示例中,ConcreteFlyweight 表示具体的共享对象,它包含一个 state_ 成员变量来表示对象的状态。FlyweightFactory 是享元工厂,它维护一个 flyweights_ 哈希表来存储已经创建的共享对象。
在 getFlyweight 方法中,如果需要的共享对象已经存在,那么直接返回它;否则,创建一个新的共享对象并将其保存到哈希表中,然后返回它。这样可以避免重复创建相同的对象,从而减少内存使用和提高性能。
优化:

在实现中,可以使用对象池技术来减少对象的创建和销毁次数,从而提高性能。

在使用享元模式时,需要考虑对象的可共享性和不可共享性,避免共享不应该共享的对象。

猜你喜欢

转载自blog.csdn.net/dica54dica/article/details/129842365