蜗牛的家
男儿当自强
posts - 48,  comments - 21,  trackbacks - 0
意图:
运用共享技术有效地支持大量细粒度的对象
适用:
一个应用程序使用了大量的对象
完全由于使用大量的对象,造成很大的存储开销
对象的大多数状态都可变为外部状态
如果删除对象的外部状态,那么可以用相对较少的共享对象取代很多组对象
UML

解析:
Flywweight模式大量使用在当一些可以被共享的对象经常使用的情况下
//test.h

#include 
<string>
#include 
<list>
//////////////////////////////////////////////////////////////////////////
using namespace std;

class Flyweight
{
public:
    
virtual ~Flyweight(){}
    
    
string GetIntrinsicState();
    
virtual void Operation(string& ExtrinsicState) = 0;
protected:
    Flyweight(
const string& state) : m_state(state){}
private:
    
string m_state;
}
;

class FlyweightFactory
{
public:
    FlyweightFactory()
{}
    
~FlyweightFactory();
    
    Flyweight
* GetFlyweight(const string& key);
private:
    list
<Flyweight*> m_listFlyweight;
}
;

class ConCreateFlyweight : public Flyweight
{
public:
    ConCreateFlyweight(
const string& state) : Flyweight(state){}
    
virtual ~ConCreateFlyweight(){}
    
    
virtual void Operation(string& ExtrinsicState);
}
;
// test.cpp : Defines the entry point for the console application.
//

#include 
"stdafx.h"
#include 
<iostream>
#include 
"test.h"

using namespace std;
//////////////////////////////////////////////////////////////////////////
inline string Flyweight::GetIntrinsicState()
{
    
return m_state;
}


FlyweightFactory::
~FlyweightFactory()
{
    list
<Flyweight*>::iterator iter1,iter2,temp;
    
for (iter1 = m_listFlyweight.begin(),iter2 = m_listFlyweight.end(); iter1 != iter2;)
    
{
        temp 
= iter1;
        
++iter1;
        delete(
*temp);
    }

    m_listFlyweight.clear();
}


Flyweight
* FlyweightFactory::GetFlyweight(const string& key)
{
    list
<Flyweight*>::iterator iter1,iter2;
    
//查看列表中是否有存在的对象
    for (iter1 = m_listFlyweight.begin(),iter2 = m_listFlyweight.end(); iter1 != iter2; ++iter1)
    
{
        
if ((*iter1)->GetIntrinsicState() == key)
        
{
            cout 
<<"The Flyweight:"<<key<<"already exits"<<endl;
            
return (*iter1);
        }

    }

    cout 
<< "Creating a new Flyweight:"<<key<<endl;
    Flyweight
* pFlyweight = new ConCreateFlyweight(key);
    m_listFlyweight.push_back(pFlyweight);
}


void ConCreateFlyweight::Operation(string& ExtrinsicState)
{
}

//////////////////////////////////////////////////////////////////////////
int main(int argc, char* argv[])
{
    
    FlyweightFactory flyweightFactory;
    flyweightFactory.GetFlyweight(
"hello");
    flyweightFactory.GetFlyweight(
"world");
    flyweightFactory.GetFlyweight(
"hello");
    
    system(
"pause");
    
return 0;
}


posted on 2008-08-20 22:54 黑色天使 阅读(457) 评论(0)  编辑 收藏 引用 所属分类: 设计模式

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理



<2008年8月>
272829303112
3456789
10111213141516
17181920212223
24252627282930
31123456

常用链接

留言簿(2)

随笔分类

随笔档案

文章档案

搜索

  •  

最新评论

阅读排行榜

评论排行榜