标签:c++ 设计模式
享元模式,运用共享技术有效的支持大量细粒度的对象。//Flyweight.h #include "stdafx.h" #include <iostream> #include <map> #include <string> using namespace std; class User { private : string m_name; public : User( string name) :m_name( name){} string GetName() { return m_name; } }; class Flyweight { public : virtual ~Flyweight(){} virtual void Operation( User* pUser) = 0; }; class ConcreteFlyweight :public Flyweight { public : virtual void Operation( User* pUser) { cout << "具体Flyweight:" <<pUser ->GetName()<< endl; } }; class UnsharedConcreteFlyweight :public Flyweight { public : virtual void Operation( User* pUser) { cout << "不共享的具体Flyweight:" << pUser->GetName() << endl; } }; class FlyweightFactory { private : map< string, Flyweight*> Flyweights; public : FlyweightFactory() { /*Flyweights.insert(make_pair("x", new ConcreteFlyweight())); Flyweights.insert(make_pair("y", new ConcreteFlyweight())); Flyweights.insert(make_pair("z", new ConcreteFlyweight()));*/ } Flyweight* GetFlyweight( string key) { map< string, Flyweight*>:: iterator it = Flyweights.find( key); if (it == Flyweights.end()) //如果不存在,实例化一个 { ConcreteFlyweight * cf = new ConcreteFlyweight (); Flyweights.insert(make_pair( key, cf)); return cf; } return it->second; } int GetCount() { return Flyweights.size(); } };
// FlyweightPattern.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "Flyweight.h" int _tmain (int argc , _TCHAR * argv []) { FlyweightFactory * flyFactory = new FlyweightFactory (); Flyweight* fx = flyFactory->GetFlyweight( "x" ); fx->Operation( new User( "小x" )); Flyweight* fy = flyFactory->GetFlyweight( "y" ); fy->Operation( new User( "小y" )); Flyweight* fz = flyFactory->GetFlyweight( "z" ); fz->Operation( new User( "小z" )); UnsharedConcreteFlyweight * uf = new UnsharedConcreteFlyweight (); uf->Operation( new User( "UnsharedConcreteFlyweight" )); cout << "共有" << flyFactory->GetCount() << "种类型" << endl; getchar(); return 0; }
wordpress用户密码加密原理及其算法分析,布布扣,bubuko.com
标签:c++ 设计模式
原文地址:http://blog.csdn.net/hk_jh/article/details/27368279