運用共享技術有效地支援大量細粒度的物件。

std::list/unordered_map),GetFlyweight(key) 先查找池中是否存在,否則建立新物件並加入池中。#ifndef FLYWEIGHT_H
#define FLYWEIGHT_H
#include <string>
#include <list>
typedef std::string STATE;
class Flyweight {
public:
virtual ~Flyweight() {}
STATE GetIntrinsicState() const;
virtual void Operation(STATE& ExtrinsicState) = 0;
protected:
Flyweight(const STATE& state) : m_State(state) {}
private:
STATE m_State;
};
class FlyweightFactory {
public:
FlyweightFactory() {}
~FlyweightFactory();
Flyweight* GetFlyweight(const STATE& key);
private:
std::list<Flyweight*> m_listFlyweight;
};
class ConcreteFlyweight : public Flyweight {
public:
ConcreteFlyweight(const STATE& state) : Flyweight(state) {}
virtual ~ConcreteFlyweight() {}
virtual void Operation(STATE& ExtrinsicState);
};
#endif
#include "Flyweight.h"
#include <iostream>
STATE Flyweight::GetIntrinsicState() const { return m_State; }
FlyweightFactory::~FlyweightFactory() {
for (auto p : m_listFlyweight) delete p;
m_listFlyweight.clear();
}
Flyweight* FlyweightFactory::GetFlyweight(const STATE& key) {
for (auto p : m_listFlyweight) {
if (p->GetIntrinsicState() == key) {
std::cout << "The Flyweight: " << key << " already exists\n";
return p;
}
}
std::cout << "Creating a new Flyweight: " << key << std::endl;
Flyweight* fw = new ConcreteFlyweight(key);
m_listFlyweight.push_back(fw);
return fw;
}
void ConcreteFlyweight::Operation(STATE& ExtrinsicState) {
// 使用外部狀態執行操作
}
#include "Flyweight.h"
int main() {
FlyweightFactory factory;
factory.GetFlyweight("hello"); // 建立新
factory.GetFlyweight("world"); // 建立新
factory.GetFlyweight("hello"); // 復用現有
return 0;
}
std::unordered_map<Key, std::shared_ptr<Flyweight>> 替代 list,查找複雜度從 O(n) 降為 O(1)。struct FontKey { string family; int size; bool bold; }),需提供雜湊函數。GetFlyweight 需加鎖或使用無鎖資料結構。