漫谈设计模式之享元模式(Flyweight)
来源:互联网 发布:python实现cnn算法 编辑:程序博客网 时间:2024/06/10 12:15
什么是享元模式?享元模式是构造型设计模式之一,它通过与其他类似对象共享数据来减少内存使用。
享元模式的角色和职责:
享元模式(Flyweight)中有一个类似Factory模式中的对象构造工厂FlyWeightFactory,当客户端程序员(client)需要一个对象的时候就会向FlyWeightFactory发出请求
对象的消息getFlyweight()消息,FlyweightFactory拥有一个管理、存储对象的“仓库”(或者叫对象池,vector等实现),getFlyWeight()消息会遍历对象池中的对象,如果已经
存在则直接返回给client,否则创建一个新的对象返回给client。当然可能也有不想被共享的对象。
抽象享元角色:所有具体享元类的父类,规定一些需要实现的公共接口。
具体享元角色:抽象享元角色的具体实现类,并实现了抽象享元角色规定的方法。
享元工厂角色:负责创建和管理享元角色。
使用场景:是以共享的方式,高效的支持大量的细粒度的对象。
示例代码:
#include <iostream>#include <map>#include <iterator>using namespace std;/** * @brief The Person class * 享元对象 */class Person{public: Person(string name,int age) { m_name = name; m_age = age; } virtual ~Person() {} virtual void printType()=0;protected: string m_name; int m_age;};/** * @brief The Teacher class * 享元细粒度对象 */class Teacher : public Person{public: Teacher(string id,string name,int age) : Person(name, age) { m_id = id; } void printType() { cout<<"name:"<<m_name<<" age:"<<m_age<<" id:"<<m_id<<endl; }private: string m_id;};/** * @brief The FlyWeightFactory class * 享元工厂,在这个案例中我们通过享元工厂要获得 * 的享元细粒度对象是Teacher */class FlyWeightFactory{public: FlyWeightFactory() { m_map.clear(); } ~FlyWeightFactory() { while(!m_map.empty()) { Person* tmp = NULL; map<string , Person*>::iterator it = m_map.begin(); tmp = it->second; m_map.erase(it); //把结点从map容器中删除 delete tmp; } } Person* getTeacher(string id) { Person* tmp = NULL; map<string ,Person*>::iterator it; it = m_map.find(id); if(it == m_map.end()) { //没有找到相同id的老师 string name; int age; cout<<"请输入老师的名字:"<<endl; cin>>name; cout<<"请输入老师的年龄:"<<endl; cin>>age; tmp = new Teacher(id,name,age); m_map.insert(pair<string,Person*>(id,tmp)); } else { tmp = it->second; } return tmp; }private: map<string ,Person*> m_map;};int main(int /*argc*/, char */*argv*/[]){ Person* p1 = NULL; Person* p2 = NULL; FlyWeightFactory* fwf = new FlyWeightFactory; p1 = fwf->getTeacher("001"); p1->printType(); p2 = fwf->getTeacher("001"); p2->printType(); delete fwf; fwf = NULL; return 0;}
运行结果:
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 - 享元模式
- 23种设计模式之享元模式(FlyWeight)
- 设计模式之享元模式(Flyweight)
- C语言rename()函数:重命名文件或目录
- AS解决Ignoring InnerClasses attribute for an anonymous inner class that doesn't come with an associate
- 常见dos命令总结
- AAC音频格式分析与解码
- 利用jquery实现超链接的失效和生效的代码示例
- 漫谈设计模式之享元模式(Flyweight)
- 基于harr的人脸检测
- 适合Web开发人员的10个CSS代码生成器
- ESB结合门户Portlet实现数据分析
- C++程序设计语言笔记(4)
- Unable to inflate view tag without class attribute
- Hbase删除表
- Python学习7-函数式编程
- java数日子