Flyweight模式

在开发时,假设创建非常多对象,就会造成非常大的内存开销。特别是大量轻量级(细粒度)的对象,还会造成内存碎片。

Flyweight模式就是运用共享技术,有效支持大量细粒度对象的设计模式。

其类结构图例如以下:
这里写图片描写叙述

在FlyweightFactory中有一个管理、存储对象的对象池,当调用GetFlyweight时会首先遍历对象池。假设已存在。则返回,否则创建新对象加入到对象池中。

有些对象可能不想被共享,那么就使用UnshareConcreteFlyweight。

实现:
//Flyweight.h

//Flywight.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 _intrinsicState;
};

class ConcreteFlyweight :public Flyweight
{
public:
    ConcreteFlyweight(string intrinsicState);
    ~ConcreteFlyweight();
    void Operation(const string& extrinsicState);
};
#endif

//Flyweight.cpp

//Flyweight.cpp

#include"Flyweight.h"
#include<iostream>
using std::cout;

Flyweight::Flyweight(string intrinsicState)
{
    _intrinsicState = intrinsicState;
}
Flyweight::~Flyweight()
{}
void Flyweight::Operation(const string& extrinsicState)
{}
string Flyweight::GetIntrinsicState()
{
    return _intrinsicState;
}

ConcreteFlyweight::ConcreteFlyweight(string intrinsicState) :Flyweight(intrinsicState)
{
    cout << "ConcreteFlyweight Build..." << std::endl;
}
ConcreteFlyweight::~ConcreteFlyweight()
{}
void ConcreteFlyweight::Operation(const string& extrinsicState)
{
    cout << "ConcreteFlyweight:内蕴[" << this->GetIntrinsicState() << "]外蕴[" 
        << extrinsicState << "]" << std::endl;
}

//FlyweightFactory.h

//FlyweightFactory.h

#ifndef _FLYWEIGHTFACTORY_H_
#define _FLYWEIGHTFACTORY_H_

#include"Flyweight.h"
#include<string>
#include<vector>
using std::string;
using std::vector;
class FlyweightFactory
{
public:
    FlyweightFactory();
    ~FlyweightFactory();
    Flyweight* GetFlyweight(const string& key);
private:
    vector<Flyweight*> _fly;

};
#endif

//FlyweightFactory.cpp

//FlyweightFactory.cpp

#include"FlyweightFactory.h"
#include<iostream>
#include<string>
#include<cassert>
using std::string;
using std::cout;

FlyweightFactory::FlyweightFactory()
{}
FlyweightFactory::~FlyweightFactory()
{}
Flyweight* FlyweightFactory::GetFlyweight(const string& key)
{
    vector<Flyweight*>::iterator it = _fly.begin();
    for (; it != _fly.end(); it++)
    {
        if ((*it)->GetIntrinsicState() == key)
        {
            cout << "already create by users..." << std::endl;
            return *it;
        }
    }

    Flyweight* fn = new ConcreteFlyweight(key);
    _fly.push_back(fn);
    return fn;
}

//main.cpp

#include"Flyweight.h"
#include"FlyweightFactory.h"
int main()
{
    FlyweightFactory* fc = new FlyweightFactory();
    Flyweight* fw1 = fc->GetFlyweight("hello");
    Flyweight* fw2 = fc->GetFlyweight("world");
    Flyweight* fw3 = fc->GetFlyweight("hello");
    return 0;
}
原文地址:https://www.cnblogs.com/blfbuaa/p/6993344.html