标签:
1.意图
运用共享技术有效地支持大量细粒度的对象。
2.动机
Flyweight模式描述了如何共享对象,使得可以细粒度地使用它们,而无需高昂的代价。flyweight是一个共享对象,它可以同时在多个场景(context)中使用,并且在每个场景中flyweight都可以作为一个独立的对象---这一点与非共享对象的实例没有区别。
3.适用性
4.结构图
5.代码实例
//Flyweight.h #include <string> class FlweightGraphicBase { public: virtual void PrintColor()=0; protected: std::string m_Color; }; class FlweightWhiteGraphic : public FlweightGraphicBase { public: FlweightWhiteGraphic(); void PrintColor(); }; class FlweightBlackGraphic : public FlweightGraphicBase { public: FlweightBlackGraphic(); void PrintColor(); };
//FlyweigtFactory.h #include <string> #include <memory> #include <map> class FlweightGraphicBase; class FlyweightFactory { public: std::shared_ptr<FlweightGraphicBase> GetFlyweight(std::string sColor); void SetFlyweight(std::string sColor, std::shared_ptr<FlweightGraphicBase> pFlyweight); private: std::map <std::string,std::shared_ptr<FlweightGraphicBase>> m_mapFlyweight; };
//Flyweight.cpp #include "Flyweight.h" #include <iostream> FlweightWhiteGraphic::FlweightWhiteGraphic() { m_Color = "White"; } void FlweightWhiteGraphic :: PrintColor() { std::cout<<"Color is :" << m_Color << std::endl; } FlweightBlackGraphic::FlweightBlackGraphic() { m_Color = "Black"; } void FlweightBlackGraphic :: PrintColor() { std::cout<<"Color is :" << m_Color << std::endl; }
//FlyweightFactory.cpp #include "FlyweightFactory.h" std::shared_ptr<FlweightGraphicBase> FlyweightFactory::GetFlyweight(std::string sColor) { auto iter = m_mapFlyweight.find(sColor); if(iter == m_mapFlyweight.end()) { return nullptr; } return iter->second; } void FlyweightFactory::SetFlyweight(std::string sColor, std::shared_ptr<FlweightGraphicBase> pFlyweight) { m_mapFlyweight[sColor] = pFlyweight; }
//Client.cpp #include "Flyweight.h" #include "FlyweightFactory.h" #include <iostream> void Insert(std::string sColor, int index,std::shared_ptr<FlweightGraphicBase> pFlweightGraphic) { std::cout<<"Posion " << index << " Insert: " << sColor << std::endl ; } int main() { std::shared_ptr<FlyweightFactory> pFlyweightFactory(new FlyweightFactory); std::shared_ptr<FlweightWhiteGraphic> pFlweightWhiteGraphic(new FlweightWhiteGraphic); std::shared_ptr<FlweightBlackGraphic> pFlweightBlackGraphic(new FlweightBlackGraphic); pFlyweightFactory->SetFlyweight("White",pFlweightWhiteGraphic); pFlyweightFactory->SetFlyweight("Black",pFlweightBlackGraphic); auto pFlyweight = pFlyweightFactory->GetFlyweight("White"); Insert("White",0,pFlyweight); pFlyweight = pFlyweightFactory->GetFlyweight("Black"); Insert("Black",1,pFlyweight); pFlyweight = pFlyweightFactory->GetFlyweight("White"); Insert("White",2,pFlyweight); pFlyweight = pFlyweightFactory->GetFlyweight("Black"); Insert("Black",3,pFlyweight); while(1); }
6.测试结果
实例代码中 所有插入的Graphic 共享黑白两种颜色,位置信息存储在外部。
7.效果
标签:
原文地址:http://www.cnblogs.com/mgp200866130/p/5575227.html