几种结构型的设计模式概析【下】——Flyweight模式,Facade模式和Proxy模式【C++实现】

在开发过程当中,有时候对于同一个或很多个大同小异的对象,我们不得不各自创建一个对象来使用它们。这种情况下,我们无意中就会造成很大的存储空间的浪费。Flywight就可以很好的解决这个问题。其UML图如下:

 

 

上图中FlywightFactory中有个对象池(VECTOR实现),用来存放我们要使用的对象,每当我们需要一个新的对象Flyweight时,就在这个对象池中检索看先前是否创建了类似的对象,如果创建了,则直接引用之前的对象,否则新创建一个Flywight对象,将该对象加入对象池,如此便可以最大限度大的节省存储空间。C++实现如下:

 

// flywight_pattener.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <iostream> #include <string> #include <vector> using namespace std; class Flyweight { protected: string characteristic; protected: Flyweight(const string & Initstr) { this->characteristic=Initstr; } public: ~Flyweight() {} virtual void Operation(const string &extern_character)=0; string & GetCharacteristic() { return this->characteristic; } }; class ConcreteFlyweight:public Flyweight { public: ConcreteFlyweight(const string & InitStr):Flyweight(InitStr) { cout<<"ConcreteFlyweight has been build!"<<endl; } ~ConcreteFlyweight() {} void Operation(const string &extern_character) { cout<<"common characteristic is "<<this->characteristic<<". other characteristic is " <<extern_character<<"."<<endl; } }; class FlyweightFactory { private: vector<Flyweight*> fly; public: FlyweightFactory() {} ~FlyweightFactory() {} Flyweight * GetFlyweight(const string &key) { vector<Flyweight*>::iterator iter; for(iter=this->fly.begin();iter!=this->fly.end();iter++) { // cout<<(*iter)->GetCharacteristic()<<endl; if( (*iter)->GetCharacteristic()==key) { cout<<"already create by users..."<<endl; return *iter; } } Flyweight *fwt=new ConcreteFlyweight(key); this->fly.push_back(fwt); return fwt; } }; int _tmain(int argc, _TCHAR* argv[]) { FlyweightFactory factory; Flyweight *fly1=factory.GetFlyweight("hello"); fly1->Operation("yello"); Flyweight *fly2=factory.GetFlyweight(" world!"); fly2->Operation("red"); Flyweight *fly3=factory.GetFlyweight("hello"); fly3->Operation("blue"); return 0; }

 

未完待续。。。

你可能感兴趣的:(几种结构型的设计模式概析【下】——Flyweight模式,Facade模式和Proxy模式【C++实现】)