C++享元模式
意图
运用共享技术有效地支持大量细粒度的对象
适用性
- 一个应用程序使用了大量的对象
- 完全由于使用大量的对象,造成很大的存储开销
- 对象的大多数状态都可变为外部状态
- 如果删除对象的外部状态,那么可以用相对较少的共享对象取代很多组对象
- 应用程序不依赖于对象标识。由于 Flyweight 对象可以被共享,对于概念上明显有别的对象,标识测试将返回真值
示意性代码
#include <iostream>
#include <unordered_set>
using namespace std;
// 抽象共享对象
class BikeFlyWeight {
public:
virtual void ride(string) = 0;
virtual void back() = 0;
virtual ~BikeFlyWeight() { };
int getState() {
return _state;
}
protected:
int _state = 0; // 0 是未使用中,1是使用中
};
// 具体共享对象
class MoBikeFlyWeight : public BikeFlyWeight {
public:
MoBikeFlyWeight(string bikeId) : _bikeId(bikeId) { }
void ride(string userName) override {
_state = 1;
cout << userName << "骑" << _bikeId << "号自行车出行!" << endl;
}
void back() override {
_state = 0;
}
private:
string _bikeId;
};
// 共享对象的建造工厂
class BikeFlyWeightFactory {
public:
~BikeFlyWeightFactory() {
delete instance;
for (auto& bike : pool) {
delete bike;
}
}
static BikeFlyWeightFactory* getInstance() {
return instance;
}
BikeFlyWeight* getBike() {
for (const auto& bike : pool) {
if (bike->getState() == 0) {
return bike;
}
}
return nullptr;
}
private:
BikeFlyWeightFactory() {
for (int i = 0; i < 2; ++i) {
pool.insert(new MoBikeFlyWeight(to_string(i)));
}
}
BikeFlyWeightFactory(const BikeFlyWeightFactory&) = delete;
BikeFlyWeightFactory(const BikeFlyWeightFactory&&) = delete;
BikeFlyWeightFactory& operator=(const BikeFlyWeightFactory&) = delete;
BikeFlyWeightFactory& operator=(const BikeFlyWeightFactory&&) = delete;
static BikeFlyWeightFactory *instance;
unordered_set<BikeFlyWeight*> pool;
};
BikeFlyWeightFactory* BikeFlyWeightFactory::instance = new BikeFlyWeightFactory();
int main() {
BikeFlyWeight* bike1 = BikeFlyWeightFactory::getInstance()->getBike();
bike1->ride("ZhangSan");
BikeFlyWeight* bike2 = BikeFlyWeightFactory::getInstance()->getBike();
bike2->ride("ZhaoSi");
bike2->back();
BikeFlyWeight* bike3 = BikeFlyWeightFactory::getInstance()->getBike();
bike3->ride("WangWu");
if (bike1 == bike2) cout << "true" << endl;
if (bike2 == bike3) cout << "true" << endl;
}