首页 > 代码库 > Flyweight
Flyweight
#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;}
Flyweight
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。