C++设计模式享元模式

以下是一个用 C++ 实现的享元模式示例代码:

 

```

#include

#include

 

class Flyweight {

private:

    std::string sharedState;

 

public:

    Flyweight(std::string state) : sharedState(state) {}

 

    void operation(std::string uniqueState) {

        std::cout << "Shared state: " << sharedState << ", Unique state: " << uniqueState << std::endl;

    }

 

};

 

class FlyweightFactory {

private:

    std::unordered_map flyweights;

 

public:

    Flyweight* getFlyweight(std::string sharedState) {

        if (flyweights.find(sharedState) == flyweights.end()) {

            flyweights[sharedState] = new Flyweight(sharedState);

        }

        return flyweights[sharedState];

    }

 

    int getFlyweightCount() {

        return flyweights.size();

    }

};

 

int main() {

    FlyweightFactory* factory = new FlyweightFactory();

 

    Flyweight* flyweight1 = factory->getFlyweight("sharedState1");

    Flyweight* flyweight2 = factory->getFlyweight("sharedState1");

 

    Flyweight* flyweight3 = factory->getFlyweight("sharedState2");

    Flyweight* flyweight4 = factory->getFlyweight("sharedState2");

 

    std::cout << "Flyweight count: " << factory->getFlyweightCount() << std::endl;

 

    flyweight1->operation("uniqueState1");

    flyweight2->operation("uniqueState2");

    flyweight3->operation("uniqueState3");

    flyweight4->operation("uniqueState4");

 

    delete factory;

    delete flyweight1;

    delete flyweight2;

    delete flyweight3;

    delete flyweight4;

 

    return 0;

}

```

 

在上面的示例中,我们通过设计 Flyweight 类和 FlyweightFactory 类,实现了一个简单的享元模式。

 

在 Flyweight 类中,我们定义了一个包含共享状态的构造函数和一个接受唯一状态的操作方法,用于展示在共享状态下的操作。

 

在 FlyweightFactory 类中,我们使用一个哈希表来存储已经创建的 Flyweight 对象。在 `getFlyweight` 方法中,如果传入的共享状态已经有对应的 Flyweight 对象,则直接返回这个对象;否则,我们创建一个新的对象并存储到哈希表中。

 

在 main 函数中,我们创建了一个 FlyweightFactory 对象,并通过它获取了两个具有相同共享状态的 Flyweight 对象,以及两个具有不同共享状态的 Flyweight 对象。通过打印 FlyweightFactory 的对象数量,我们证明了在获取具有相同共享状态的 Flyweight 对象时,它们实际上使用了同一个对象。最后,我们分别调用以上四个对象的 `operation` 方法,演示每个对象在不同唯一状态下的操作。

 

在程序结束后,我们还需要手动释放创建的对象,以避免内存泄漏。

你可能感兴趣的:(c++)