大胖的部落格

Just a note

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  112 随笔 :: 0 文章 :: 3 评论 :: 0 Trackbacks
对同样内容的对象,只创建一份。
需要显示对象时,若对象存在,则返回已存在对象的地址;若不存在,则创建对象再返回。

#include <iostream>
#include 
<string>
#include 
<list>

using namespace std;

//封装了string
class Flyweight
{
public:
    Flyweight(
string s):str(s){}
    
string GetStr(){return str;}
    
void Print() const {cout<<str<<endl;}
private:
    
string    str;
}
;

//提供了返回flyweight的接口
class FlyweightFactory
{
public:
    
~FlyweightFactory()
    
{
        list
<Flyweight*>::iterator it;
        
for(it=lf.begin(); it!=lf.end(); it++)
        
{
            delete (
*it);
        }

    }


    
//若不存在则新建,若存在则返回存在的元素
    const Flyweight* GetFlyweight(const string& s)
    
{
        list
<Flyweight*>::iterator it;
        
for(it=lf.begin(); it!=lf.end(); it++)
        
{
            
if((*it)->GetStr() == s+"_fly")
            
{
                cout
<<"exist: ";
                
return *it;
            }

        }

        Flyweight 
*= new Flyweight(s+"_fly");
        lf.push_back(p);
        cout
<<"new: ";
        
return p;
    }

private:
    list
<Flyweight*> lf;
}
;

int main()
{
    FlyweightFactory 
*= new FlyweightFactory;
    p
->GetFlyweight("hello")->Print();
    p
->GetFlyweight("hello")->Print();
    p
->GetFlyweight("hello")->Print();
    p
->GetFlyweight("dog")->Print();
    p
->GetFlyweight("dog")->Print();
    p
->GetFlyweight("hello")->Print();

    delete p;

    
return 0;
}
posted on 2009-06-09 16:55 大胖 阅读(108) 评论(0)  编辑 收藏 引用 所属分类: Design Pattern

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