设计模式-FlyWeight(结构型模式) 针对 需要创建大量对象的情形,被共享的状态作为内部状态,不被共享的状态作为外部状态
以下代码来源: 设计模式精解-GoF 23种设计模式解析附C++实现源码
//Flyweight.h
#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 _intrinsicState; }; class ConcreateFlyWeight :public FlyWeight { public: ConcreateFlyWeight(std::string intrinsicState); ~ConcreateFlyWeight(); void Operation(const std::string& extrinsicState); protected: private: };
//Flyweight.cpp
#include"Flyweight.h" #include<iostream> FlyWeight::FlyWeight(std::string intrinsicState) { this->_intrinsicState = intrinsicState; } FlyWeight::~FlyWeight(){} void FlyWeight::Operation(const std::string& extrinsicState) { } std::string FlyWeight::GetIntrinsicState() { return this->_intrinsicState; } 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:内部[" << this->GetIntrinsicState() << "]外部[" << extrinsicState << "]" << std::endl; }
//FlyWeightFactory.h
#pragma once #include"Flyweight.h" #include<vector> #include<string> class FlyWeightFactory { public: FlyWeightFactory(); ~FlyWeightFactory(); FlyWeight* GetFlyWeight(const std::string& key); protected: private: std::vector<FlyWeight*>_fly; };
//FlyWeightFactory.cpp
#include"FlyWeightFactory.h" #include<iostream> #include<string> FlyWeightFactory::FlyWeightFactory(){} FlyWeightFactory::~FlyWeightFactory(){} FlyWeight* FlyWeightFactory::GetFlyWeight(const std::string& key) { for (std::vector<FlyWeight*>::iterator it = _fly.begin(); it != _fly.end(); ++it) { if ((*it)->GetIntrinsicState() == key) { std::cout << "Already created by users..." << std::endl; return *it; } } FlyWeight* fn = new ConcreateFlyWeight(key); _fly.push_back(fn); return fn; }
//main.cpp
#include"Flyweight.h" #include"FlyWeightFactory.h" #include<string> int main(int args, char* argv) { FlyWeightFactory* flyfac = new FlyWeightFactory(); FlyWeight* fw1 = flyfac->GetFlyWeight("Hello"); FlyWeight* fw2 = flyfac->GetFlyWeight("World"); FlyWeight* fw3 = flyfac->GetFlyWeight("Hello"); getchar(); return 0; }