设计模式--享元模式实现C++
生活随笔
收集整理的這篇文章主要介紹了
设计模式--享元模式实现C++
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
/*********************************
*設(shè)計模式--享元模式實(shí)現(xiàn)
*C++語言
*Author:WangYong
*Blog:http://www.cnblogs.com/newwy
********************************/
#include <iostream>
#include <cassert>
#include <vector>
#include <string>
using namespace std;
class Flyweight
{public:virtual ~Flyweight(){}virtual void Operation(const string & extrinsicState){}string GetIntrinsicState(){return this->_intrinsicState;}protected:Flyweight(string intrinsicState){this->_intrinsicState = _intrinsicState;}private:string _intrinsicState;
};
class ConcreteFlyweight:public Flyweight
{public:ConcreteFlyweight(string intrinsicState):Flyweight(intrinsicState){cout<<"ConcreteFlyweight Build ...."<<intrinsicState<<endl;}~ConcreteFlyweight(){}void Operation(const string & extrinsicState){cout<<"ConcreteFlyweight:內(nèi)蘊(yùn)"<<this->GetIntrinsicState()<<"ConcreteFlyweight:外蘊(yùn)"<<extrinsicState<<endl;}
};
class FlyweightFactory
{public:FlyweightFactory(){}~FlyweightFactory(){}Flyweight * GetFlyweight(const string &key){vector<Flyweight *>::iterator it = _fly.begin();for(;it != _fly.end(); it++){if( (*it)->GetIntrinsicState() == key)cout<<"already created by users..."<<endl;return *it;}Flyweight *fn = new ConcreteFlyweight(key);_fly.push_back(fn);return fn; }private:vector<Flyweight*> _fly;
};
int main()
{FlyweightFactory *fc = new FlyweightFactory();Flyweight * fw1 = fc->GetFlyweight("hello");Flyweight * fw2 = fc->GetFlyweight("world!");Flyweight * fw3 = fc->GetFlyweight("hello");
}
轉(zhuǎn)載于:https://www.cnblogs.com/newwy/archive/2010/10/18/1855224.html
總結(jié)
以上是生活随笔為你收集整理的设计模式--享元模式实现C++的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 图片轮播,鼠标放上去即停止,鼠标移除即播
- 下一篇: C/C++中善用大括号