享元模式(FlyweightPattern)
基本概念:
享元模式通过重用现有的对象,从而减少创建对象的数量,达到减少内存占用和提高性能的目的。
目的是什么:
主要解决什么样的问题:
有时需要使用大量的同类对象来进行一项工作。
重点剖析:
原件要有一个关键特征作为key;
一个map,用于存放key-value;
举例:
不同的汽车可能采用相同的零件(又是汽车)。对于这种相同的零件(component),我们进行一次原型设计,并将他们放到仓库里(map)。在下次研发其他车型时,如果需要相同的零件可直接从仓库里将原型设计拿出来进行生产,如果仓库里没有,则进行新的原型设计,并将设计好的原型放到仓库里,以备下次使用。
上代码:
//原型设计
//H
#pragma once
#include <iostream>
#include <string>
#include <map>
#include <assert.h>
using namespace std;
class iron
{
public:
iron(void);
~iron(void);
virtual void draw() = 0;
};
class component: public iron
{
public:
component(){}
component(string _color);
~component();
component(const component&c);
void draw();
void setwidth(int _width);
void setlength(int _length);
private:
string color;
int width;
int length;
};
//CPP
#include "shape.h"
iron::iron(void)
{
}
iron::~iron(void)
{
}
component::component(string _color)
{
color = _color;
}
component::~component()
{
//NULL
}
void component::setwidth(int _width)
{
width = _width;
}
void component::setlength(int _length)
{
length = _length;
}
component::component(const component& c)
{
color = c.color;
width = c.width;
length = c.length;
}
void component::draw()
{
cout<<"Component:"<<"color="<<color<<" "<<"width="<<width<<""<<"length="<<length<<" "<<endl;
}
//原型仓库
//H
#pragma once
#include "shape.h"
class componentFactory
{
public:
componentFactory(void);
~componentFactory(void);
component& getComponent(stringcolor, component& cp);
int getMapSize();
private:
map<string, component>ccm; //此处是重点
};
//CPP
#include "componentFactory.h"
componentFactory::componentFactory(void)
{
}
componentFactory::~componentFactory(void)
{
}
component& componentFactory::getComponent(string color, component&cp)
{
if(ccm.find(color) != ccm.end())
cp = ccm[color];
else{
component tmp(color);
tmp.setwidth(10);
tmp.setlength(20);
ccm.insert(pair<string,component>(color,tmp));
cp = tmp;//不调用复制构造函数
}
return cp;//调用复制构造函数
}
int componentFactory::getMapSize()
{
return ccm.size();
}
//实验
#include <iostream>
#include "shape.h"
#include "componentFactory.h"
int main()
{
component ob;
componentFactory* fac = newcomponentFactory();
cout<<"Map size= "<<fac->getMapSize()<<endl;
component c1 = fac->getComponent("red",ob);
cout<<"Map size= "<<fac->getMapSize()<<endl;
component c2 = fac->getComponent("red",ob);
c2.draw();
return 0;
}