设计模式之享元模式
英文:Flyweight模式
#pragma once #include <string> class Flyweight { public: virtual ~Flyweight(); virtual void Operation(const std::string &extrinsicState); std::string GetIntrinsicState(); protected: Flyweight(std::string intrinsicState); private: std::string m_intrinsicState; };
#include "Flyweight.h" Flyweight::Flyweight(std::string intrinsicState) { this->m_intrinsicState = intrinsicState; } Flyweight::~Flyweight() { } void Flyweight::Operation(const std::string &extrinsicState) { } std::string Flyweight::GetIntrinsicState() { return this->m_intrinsicState; }
#pragma once #include "Flyweight.h" class ConcreateFlyweight : public Flyweight { public: ConcreateFlyweight(std::string intrinsicState); ~ConcreateFlyweight(); void Operation(const std::string &extrinsicState); };
#include "ConcreateFlyweight.h" #include <iostream> ConcreateFlyweight::ConcreateFlyweight(std::string intrinsicState) : Flyweight(intrinsicState) { std::cout << "ConcreateFlyweight Build..." << intrinsicState << std::endl; } ConcreateFlyweight::~ConcreateFlyweight() { } void ConcreateFlyweight::Operation(const std::string &extrinsicState) { std::cout << "ConcreateFlyweight:IN[" << this->GetIntrinsicState() << "]OUT[" << extrinsicState << "]" << std::endl; }
#pragma once #include "Flyweight.h" #include <string> #include <vector> class FlyweightFactory { public: FlyweightFactory(); ~FlyweightFactory(); Flyweight *GetFlyweight(const std::string &key); private: std::vector<Flyweight *> m_vec_FW; };
#include "FlyweightFactory.h" #include "ConcreateFlyweight.h" #include <iostream> FlyweightFactory::FlyweightFactory() { } FlyweightFactory::~FlyweightFactory() { for (std::vector<Flyweight *>::iterator it = m_vec_FW.begin(); it < m_vec_FW.end(); it++) { delete *it; *it = NULL; } m_vec_FW.clear(); } Flyweight *FlyweightFactory::GetFlyweight(const std::string &key) { std::vector<Flyweight *>::iterator it = m_vec_FW.begin(); for (; it != m_vec_FW.end(); it++) { if ((*it)->GetIntrinsicState() == key) { std::cout << "already created by user..." << std::endl; return *it; } } Flyweight *fw = new ConcreateFlyweight(key); m_vec_FW.push_back(fw); return fw; }
测试
#include <iostream> #include "FlyweightFactory.h" int main() { FlyweightFactory *fc = new FlyweightFactory(); Flyweight *fw1 = fc->GetFlyweight("hello"); Flyweight *fw2 = fc->GetFlyweight("world!"); Flyweight *fw3 = fc->GetFlyweight("hello"); if (fc) { delete fc; fc = NULL; } std::cout << "Hello World!\n"; }

浙公网安备 33010602011771号