Flyweight模式

来源:互联网 发布:网络歌曲么么哒 编辑:程序博客网 时间:2024/05/17 04:22
Flyweight模式
一、意图:
    运用共享技术有效地支持大量细粒度的对象。
二、说明:
    Flyweight模式对那些通常因为数量太大而难以用对象来表示的概念或实体进行建模。
三、举例:
    文档编辑器,可以为每个字母创建一个Flyweight。每个享元存储一个字符代码,但它在文档中的位置和排版风格
可以在字符出现时由正文排版算法和使用的格式化命令决定。字符代码是内部状态,而其他的信息则是外部状态。
四、C++代码示例:
//flyweight.h
#ifndef FLYWEIGHT_H;#define FLYWEIGHT_H#include <string>using std::string;class Flyweight{public:    virtual ~Flyweight();    virtual void Operation(const string& extrinsicState);    string GetIntrinsicState();protected:    Flyweight(string intrinsicState);private:    string m_intrinsicState;};class ConcreteFlyweight : public Flyweight{public:    ConcreteFlyweight(string intrinsicState);    ~ConcreteFlyweight();    void Operation(const string &extrinsicState);};#endif // FLYWEIGHT_H

//flyweight.cpp
#include "flyweight.h"#include <iostream>using namespace std;Flyweight::Flyweight(string intrinsicState){    this->m_intrinsicState = intrinsicState;}Flyweight::~Flyweight(){}void Flyweight::Operation(const string &extrinsicState){}string Flyweight::GetIntrinsicState(){    return this->m_intrinsicState;}ConcreteFlyweight::ConcreteFlyweight(string intrinsicState)    : Flyweight(intrinsicState){    cout << "ConcreteFlyweight Build..." << intrinsicState << endl;}ConcreteFlyweight::~ConcreteFlyweight(){}void ConcreteFlyweight::Operation(const string &extrinsicState){    cout << "ConcreteFlyweight::Operation: 内部 " << this->GetIntrinsicState()         << " 外部 " << extrinsicState <<endl;}

//flyweightfactory.h
#ifndef FLYWEIGHTFACTORY_H#define FLYWEIGHTFACTORY_H#include "flyweight.h"#include <string>#include <vector>using namespace std;class FlyweightFactory{public:    FlyweightFactory();    ~FlyweightFactory();    Flyweight* GetFlyweight(const string&key);private:    vector<Flyweight*> m_fly;};#endif // FLYWEIGHTFACTORY_H

//flyweightfactory.cpp
#include "flyweightfactory.h"#include <iostream>#include <cassert>FlyweightFactory::FlyweightFactory(){}FlyweightFactory::~FlyweightFactory(){}Flyweight* FlyweightFactory::GetFlyweight(const string &key){    vector<Flyweight*>::iterator iter = m_fly.begin();    for(; iter != m_fly.end(); ++iter){        if((*iter)->GetIntrinsicState() == key){            cout << "already created by users" << endl;            return *iter;        }    } //注意iter是指向指针的指针    Flyweight* fly = new ConcreteFlyweight(key);    m_fly.push_back(fly);    return fly;}
//main.cpp
#include <iostream>#include "flyweight.h"#include "flyweightfactory.h"#include <iostream>using namespace std;int main(){    FlyweightFactory* ff = new FlyweightFactory();    Flyweight* f1 = ff->GetFlyweight("hello");    Flyweight* f2 = ff->GetFlyweight("world");    Flyweight* f3 = ff->GetFlyweight("hello");    return 0;}
运行结果:
五、效果
    使用Flyweight模式时,传输、查找和计算外部状态都会产生运行时的开销,尤其当Flyweight原先被存储在内部
状态时。然而,空间上的节省抵消了这些开销,共享的Flyweight越多,空间节省多大。
    
                                             
0 0
原创粉丝点击