博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
《设计模式》学习笔记——享元模式
阅读量:4111 次
发布时间:2019-05-25

本文共 2120 字,大约阅读时间需要 7 分钟。

享元模式(Flyweight Pattern)是一种软件设计模式。

 它使用共享物件,用来尽可能减少内存使用量以及分享资讯给尽可能多的相似物件;适合用于当大量物件只是重复因而导致无法令人接受的使用大量内存。

通常物件中的部分状态是可以分享。常见做法是把它们放在外部数据结构,当需要使用时再将它们传递给享元。

享元模式通过共享的方式,高效的支持大量的细粒度的操作。

 

FlyweightPattern.h

#pragma once#include
#include
#include
class Person{public: Person(std::string name,int age):m_name_string(name),m_age_int(age) {}; virtual ~Person() {}; virtual void printT() = 0;private: protected: std::string m_name_string; int m_age_int;};class Teacher :public Person{public: Teacher(std::string name, int age, std::string id) :Person(name, age), m_id_string(id){}; virtual ~Teacher() {}; virtual void printT(){std::cout << "name:"<
<<" age:"<
<<" id:"<
<< std::endl;}private:protected: std::string m_id_string; };// 完成老师节点的存储class FlyweightTeacherFactory{public: FlyweightTeacherFactory() { m_teacherMap.clear(); } ~FlyweightTeacherFactory() { std::map
::iterator it; while (!m_teacherMap.empty()) { it = m_teacherMap.begin(); delete (it->second); m_teacherMap.erase(it); } } Person * getTeacher(std::string id) { std::map
::iterator it= m_teacherMap.find(id); if (it == m_teacherMap.end()) { // 如果id不存在,创建新的对象,插曲map后返回 std::string name; int age; std::cout << "请输入姓名,年龄"; std::cin >> name>>age; Teacher* teacher = new Teacher(name, age, id); // 新对象插入容器 m_teacherMap.insert(std::pair
(id,teacher)); return teacher; } else { // 如果id存在,直接返回查找到的结果 return it->second; } return nullptr; }private: std::map
m_teacherMap;protected:};class FlyweightPattern{public: FlyweightPattern() {}; ~FlyweightPattern() {};};

 

FlyweightPattern.cpp

#include "FlyweightPattern.h"

 

mainTest.cpp

#include
#include
#include"FlyweightPattern.h"int main(void){ FlyweightTeacherFactory* flyweightTeacherFactory = new FlyweightTeacherFactory; Teacher* teacher= dynamic_cast
(flyweightTeacherFactory->getTeacher("001")); teacher->printT(); Teacher* teacher2 = dynamic_cast
(flyweightTeacherFactory->getTeacher("001")); teacher2->printT(); delete teacher; delete teacher2; delete flyweightTeacherFactory; system("pause"); return 0;}

 

转载地址:http://zemsi.baihongyu.com/

你可能感兴趣的文章
【2021-MOOC-浙江大学-陈越、何钦铭-数据结构】树
查看>>
MySQL主从复制不一致的原因以及解决方法
查看>>
RedisTemplate的key默认序列化器问题
查看>>
序列化与自定义序列化
查看>>
ThreadLocal
查看>>
从Executor接口设计看设计模式之最少知识法则
查看>>
OKhttp之Call接口
查看>>
application/x-www-form-urlencoded、multipart/form-data、text/plain
查看>>
关于Content-Length
查看>>
WebRequest post读取源码
查看>>
使用TcpClient可避免HttpWebRequest的常见错误
查看>>
EntityFramework 学习之一 —— 模型概述与环境搭建 .
查看>>
C# 发HTTP请求
查看>>
初试visual studio2012的新型数据库LocalDB
查看>>
启动 LocalDB 和连接到 LocalDB
查看>>
Palindrome Number --回文整数
查看>>
Reverse Integer--反转整数
查看>>
Container With Most Water --装最多水的容器(重)
查看>>
Longest Common Prefix -最长公共前缀
查看>>
Letter Combinations of a Phone Number
查看>>