设计模式之享元模式(Flyweight)
来源:互联网 发布:小米网络收音机改软件 编辑:程序博客网 时间:2024/05/21 13:56
优点:1)大幅度地降低内存中对象的数量
#include <iostream>#include <vector>using namespace std;class FlyWeight{public: virtual ~FlyWeight(){} string getInstrinsicState(){return _state;} virtual void Operation(string &state) = 0;protected: FlyWeight(const string &state){_state = state;}private: string _state;};class ConcreateFlyweight : public FlyWeight{public: ConcreateFlyweight(const string &state):FlyWeight(state){} virtual ~ConcreateFlyweight(){} virtual void Operation(string &state){cout << "ConcreateFlyweight:" << state.data() << endl;}};class FlyWeightFactory{public: FlyWeightFactory(){} ~FlyWeightFactory() { for(int i = 0; i < _vector.size(); ++i) delete _vector.at(i); _vector.clear(); } FlyWeight *getFlyWeight(const string&key) { for(int i = 0; i < _vector.size(); ++i) { string state = _vector.at(i)->getInstrinsicState(); if(!strcmp(state.data(),key.data())) { cout << "The Flyweight:" << key.data() << " already exists" << endl; return _vector.at(i); } } std::cout << "Creating a new Flyweight:" << key.data() << std::endl; FlyWeight *flyWeight = new ConcreateFlyweight(key); _vector.push_back(flyWeight); return flyWeight; }private: vector<FlyWeight *> _vector;};int main(){ FlyWeightFactory flyWeightFactory; FlyWeight *f1 = flyWeightFactory.getFlyWeight("hello"); FlyWeight *f2 = flyWeightFactory.getFlyWeight("world"); flyWeightFactory.getFlyWeight("hello"); return 0;}
运行结果:
Creating a new Flyweight:hello
Creating a new Flyweight:world
The Flyweight:hello already exists
阅读全文
0 0
- 设计模式之Flyweight享元模式
- 【设计模式】之 Flyweight享元模式
- 设计模式之享元模式(Flyweight)
- 设计模式之享元模式(Flyweight)
- 设计模式之享元模式Flyweight
- 设计模式之Flyweight(享元) FlyWeight模式
- 设计模式之Flyweight(享元) FlyWeight模式
- 设计模式之Flyweight(享元) FlyWeight模式
- 设计模式之Flyweight(享元) FlyWeight模式
- 设计模式之Flyweight(享元) FlyWeight模式
- 设计模式之Flyweight(享元) FlyWeight模式
- 设计模式之Flyweight(享元) FlyWeight模式
- 设计模式之Flyweight(享元) FlyWeight模式
- 设计模式之Flyweight(享元)
- 设计模式之Flyweight(享元)
- 设计模式之十------FlyWeight(享元)
- 设计模式之Flyweight(享元)
- 设计模式之享元模式,内存共享模式,Flyweight
- [Leetcode] 246. Strobogrammatic Number 解题报告
- Java实现-带重复元素的子集
- 操作系统性能分析思路总结
- WordPress 安全设置之网站隐藏登陆网址,防止黑客
- SAP打印机原理、打印配置及打印操作
- 设计模式之享元模式(Flyweight)
- C# 线程的定义和使用
- VTK基础学习
- XStream使用笔记
- React+NodeJS+Express 环境搭建与部署
- 机器学习—Caffe下载安装编译-测试MNIST数据集
- <NOIP> 9 . P1307 数字反转
- 第1章 Python笔记 基础知识
- Java实现-全排列