1 Star 0 Fork 621

私有仓库/DesignPattern

forked from Micooz/DesignPattern 
加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
FlyweightPattern.cpp 1.32 KB
一键复制 编辑 原始数据 按行查看 历史
Micooz 提交于 2014-10-09 11:46 +08:00 . 加入解释器模式,迭代器模式
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Flyweight {
public:
Flyweight(string state):_state(state) {
}
virtual void Operation(const string&state) { }
string GetState()const { return _state; }
virtual ~Flyweight() { }
private:
string _state;
};
class ConcreteFlyweight :public Flyweight {
public:
ConcreteFlyweight(string state)
:Flyweight(state) {
cout << "ConcreteFlyweight Build..." << state << endl;
}
void Operation(const string& state) {
cout << "ConcreteFlyweight " << GetState() << " \\ " << state << endl;
}
};
class FlyweightFactory {
public:
Flyweight *GetFlyweight(std::string key) {
for (auto fly : _flys) {
if (fly->GetState() == key) {
cout << "already created by users..." << endl;
return fly;
}
}
Flyweight *fn = new ConcreteFlyweight(key);
_flys.push_back(fn);
return fn;
}
private:
std::vector<Flyweight*> _flys;
};
int main() {
FlyweightFactory *fc = new FlyweightFactory();
Flyweight *fw1 = fc->GetFlyweight("hello");
Flyweight *fw2 = fc->GetFlyweight("world");
Flyweight *fw3 = fc->GetFlyweight("hello");
delete fw1;
delete fw2;
//delete fw3;
delete fc;
return 0;
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/sydev/DesignPattern.git
git@gitee.com:sydev/DesignPattern.git
sydev
DesignPattern
DesignPattern
master

搜索帮助