标签:des style blog io ar color os sp for
#include <iostream> #include <vector> using namespace std; #define SHARE_FLAG string #define DESTROY_POINTER(ptr) if (ptr) { delete ptr; ptr = NULL; } class Flyweight { public: Flyweight(SHARE_FLAG flag) : m_shareFlag(flag) {} virtual void Operation()=0; virtual SHARE_FLAG GetShareFlag() { return m_shareFlag; } protected: SHARE_FLAG m_shareFlag; }; class ConcreteFlyweight : public Flyweight { public: ConcreteFlyweight(SHARE_FLAG flag) : Flyweight(flag) {} ~ConcreteFlyweight() {} void Operation() { cout<<"share flag:"<<m_shareFlag<<endl; } }; class FactoryFlyweight { public: FactoryFlyweight() {} ~FactoryFlyweight(); Flyweight* CreateFlyweight(SHARE_FLAG flag); private: vector<Flyweight*> m_objectList; }; FactoryFlyweight::~FactoryFlyweight() { for (unsigned int i = 0; i < m_objectList.size(); i++) { Flyweight* pTmp = m_objectList[i]; DESTROY_POINTER(pTmp); } m_objectList.clear(); } Flyweight* FactoryFlyweight::CreateFlyweight(SHARE_FLAG flag) { for (unsigned int i = 0; i < m_objectList.size(); i++) { if (m_objectList[i]->GetShareFlag() == flag) { cout<<"cache object["<<m_objectList[i]->GetShareFlag()<<"]"<<endl; return m_objectList[i]; } } ConcreteFlyweight* newObj = new ConcreteFlyweight(flag); m_objectList.push_back(newObj); return newObj; } int main(int argc, char *argv[]) { FactoryFlyweight* pFactory = NULL; Flyweight* pFlyweight = NULL; pFactory = new FactoryFlyweight; pFlyweight = pFactory->CreateFlyweight("object1"); pFlyweight = pFactory->CreateFlyweight("object2"); pFlyweight = pFactory->CreateFlyweight("object3"); pFlyweight = pFactory->CreateFlyweight("object1"); pFlyweight = pFactory->CreateFlyweight("object3"); DESTROY_POINTER(pFactory); return 0; }
标签:des style blog io ar color os sp for
原文地址:http://www.cnblogs.com/stanley198610281217/p/4159500.html