Flyweight

Flyweight
对同样内容的对象,只创建一份。
需要显示对象时,若对象存在,则返回已存在对象的地址;若不存在,则创建对象再返回。

#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;
}

你可能感兴趣的:(Flyweight)