《设计模式》学习笔记——享元模式

享元模式(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:"<::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;
}

 

你可能感兴趣的:(C++,学习日记,设计模式,设计模式,享元模式,Flyweight,Pattern)