1. 程式人生 > >FlyWeight 享元模式

FlyWeight 享元模式

#include <cstdlib>
#include <iostream>
#include <vector>
using namespace std;
class FlyWeight
{
protected:
  std::string m_name;
public:
  FlyWeight(std::string str):m_name(str){}
  virtual ~FlyWeight(){cout<<"FlyWeight 基類析構"<<endl;}
  std::string GetName()const{return m_name;}
};
class FlyWeightConcreteA:public FlyWeight
{
public:
  virtual ~FlyWeightConcreteA(){cout<<"FlyWeightConcreteA 子類析構"<<endl;}
  FlyWeightConcreteA(std::string str):FlyWeight(str + "A"){}
};
class FlyWeightConcreteB:public FlyWeight
{
public:
  virtual ~FlyWeightConcreteB(){cout<<"FlyWeightConcreteB 子類析構"<<endl;}
  FlyWeightConcreteB(std::string str):FlyWeight(str + "B"){}
};
class FlyWeightFactory
{
protected:
  vector<FlyWeight*> m_vector;
public:
  virtual FlyWeight* GetFlyWeight(std::string str) = 0;
  virtual ~FlyWeightFactory()
  {
    cout<<"FlyWeightFactory 基類析構"<<endl;
    vector<FlyWeight*>::iterator it = m_vector.begin(),itend = m_vector.end();
    for(;it != itend; it++)
    {
      delete *it;
    }
    m_vector.clear();
  }
};
class FlyWeightFactoryA:public FlyWeightFactory
{
public:
  virtual ~FlyWeightFactoryA(){cout<<"FlyWeightFactoryA 子類析構"<<endl;}
  virtual FlyWeight* GetFlyWeight(std::string str)
  {
    vector<FlyWeight*>::iterator it = m_vector.begin(),itend = m_vector.end();
    for(;it != itend; it++)
    {
      if((*it)->GetName() == (str + "A"))return *it;
    }
    FlyWeight* pFly = new FlyWeightConcreteA(str);
    m_vector.push_back(pFly);
    return pFly;
  }
};
class FlyWeightFactoryB:public FlyWeightFactory
{
public:
  virtual ~FlyWeightFactoryB(){cout<<"FlyWeightFactoryB 子類析構"<<endl;}
  virtual FlyWeight* GetFlyWeight(std::string str)
  {
    vector<FlyWeight*>::iterator it = m_vector.begin(),itend = m_vector.end();
    for(;it != itend; it++)
    {
      if((*it)->GetName() == (str + "B"))return *it;
    }
    FlyWeight* pFly = new FlyWeightConcreteB(str);
    m_vector.push_back(pFly);
    return pFly;
  }
};
void Do(FlyWeightFactory* pFac,int x,int y)
{
  FlyWeight* pFly = pFac->GetFlyWeight("hello");
  cout<<"數出字串:"<<pFly->GetName()<<"在x="<<x<<",y="<<y<<endl;
  pFly = pFac->GetFlyWeight("world");
  cout<<"數出字串:"<<pFly->GetName()<<"在x="<<x<<",y="<<y<<endl;
  pFly = pFac->GetFlyWeight("hello");
  cout<<"數出字串:"<<pFly->GetName()<<"在x="<<x<<",y="<<y<<endl;
}
int main(int argc, char *argv[])
{
    FlyWeightFactory* oneFac = new FlyWeightFactoryA;
    cout<<"----------------"<<endl;
    Do(oneFac,10,10);
    cout<<"----------------"<<endl;
    delete oneFac;
    oneFac = new FlyWeightFactoryB;
    cout<<"----------------"<<endl;
    Do(oneFac,100,100);
    cout<<"----------------"<<endl;
    delete oneFac;
    system("PAUSE");
    return EXIT_SUCCESS;
}