C++设计模式之享元模式(FlyWeight)

来源:互联网 发布:网络维护maxingit 编辑:程序博客网 时间:2024/05/29 15:12
FlyWeight享元模式,其实就是为C++在构造大量对象的时候进行减肥,以减少内存的使用,其特征是工厂类里包含了缓冲区模式,以下两种实现的区别就是第一种汽车有将其m_Brand的品牌提取到一个FlyWeight,将公共数据成员共享!#include "StdAfx.h"#include <SSTREAM>#include<iostream>#include<fstream>#include<malloc.h>#include <windows.h>#include <list>#include <map>using namespace std;class CarBody{//汽车public:    CarBody(string Wheel,string Light,string Engine):      m_Wheel(Wheel),m_Light(Light),m_Engine(Engine)    {     }protected:private:    string m_Wheel;    string m_Light;    string m_Engine;}; class FlyWeightCar{//享元汽车,将品牌的数据成员集合在一起public:    FlyWeightCar(string Brand,CarBody* pCar):      m_Car(pCar),m_Brand(Brand)      {       }protected:private:    string m_Brand;    CarBody* m_Car;}; class FlyWeightFactory{//享元工厂public:    FlyWeightCar* GetCar(string Brand,string Wheel,string Light,string Engine)    {//享元模式的缓冲区        if (m_FlyCars[Brand]!=NULL)        {            return m_FlyCars[Brand];        }else{            CarBody* pNew=new CarBody(Wheel,Light,Engine);            FlyWeightCar* pNewFlyWeightCar=new FlyWeightCar(Brand,pNew);            m_FlyCars[Brand]=pNewFlyWeightCar;        }    }protected:private:    map<string ,FlyWeightCar*> m_FlyCars;//缓冲区};int main(void) {     FlyWeightFactory pFactory;    for (int i=0;i<2000;i++)    {        pFactory.GetCar("BMW","轮子","灯光","引擎");    }    return 0; }第二种:#include "StdAfx.h"#include <SSTREAM>#include<iostream>#include<fstream>#include<malloc.h>#include <windows.h>#include <list>#include <map>using namespace std;class FlyWeight{//基类public:    virtual void Operation()=0;protected:private:};class ConcreteFlyWeight:public FlyWeight{//继承与Flyweightpublic:    string m_Key;    virtual void Operation()    {        printf("%s",m_Key.c_str());    }protected:private:};class FlyWeightFactory{public:    map<string,ConcreteFlyWeight*> m_FlyWeightPool;//缓冲区    ConcreteFlyWeight* GetConcreteFlyweight(string key)    {        if (NULL==m_FlyWeightPool[key])        {            ConcreteFlyWeight* pFlyWeight=new ConcreteFlyWeight();            pFlyWeight->m_Key=key;            m_FlyWeightPool[key]=pFlyWeight;        }        return m_FlyWeightPool[key];    }protected:private:};int main(void) {     FlyWeightFactory pFactory;    FlyWeight* p1=pFactory.GetConcreteFlyweight("www.qq.com");    FlyWeight* p2=pFactory.GetConcreteFlyweight("www.baidu.com");    FlyWeight* p3=pFactory.GetConcreteFlyweight("www.qq.com");    FlyWeight* p4=pFactory.GetConcreteFlyweight("www.baidu.com");    p1->Operation();    p2->Operation();    p3->Operation();    p4->Operation();    return 0; }

0 0
原创粉丝点击