// Flyweight. cpp: defines the entry point of the console application.
//
# Include "stdafx. H"
# Include <iostream>
# Include <list>
# Include <string>
Using namespace STD;
Typedef string state;
Class flyweight
{
Public:
State getintrinsicstate ()
{
Return m_state;
}
Virtual void operation (State & extrinsic) = 0;
Protected:
Flyweight (const State & S): m_state (s)
{
}
PRIVATE:
State m_state;
};
Class concreteflyweight: Public flyweight
{
Public:
Concreteflyweight (const State & S): flyweight (s)
{
}
Virtual ~ Concreteflyweight ()
{
}
Virtual void operation (State & extrinsic)
{
Cout <"Operation of concreteflyweight" <Endl;
}
};
Class flyweightfactory
{
Public:
Flyweightfactory ()
{
}
Virtual ~ Flyweightfactory ()
{
List <flyweight *>: iterator ITER, temp;
For (iter = m_listflyweight.begin (); iter! = M_listflyweight.end (); ITER ++)
{
Temp = ITER;
++ ITER;
Delete (* temp );
}
}
Flyweight * getflyweight (const State & Key)
{
List <flyweight *>: iterator ITER;
For (iter = m_listflyweight.begin (); iter! = M_listflyweight.end (); ITER ++)
{
If (* ITER)-> getintrinsicstate () = key)
{
Cout <"the flyweight:/" "<key <"/"already exists" <Endl;
Return (* ITER );
}
}
Cout <"create new instance of concreteflyweight" <Endl;
Flyweight * pflyweight = new concreteflyweight (key );
M_listflyweight.push_back (pflyweight );
Return pflyweight;
}
PRIVATE:
List <flyweight *> m_listflyweight;
};
Int _ tmain (INT argc, _ tchar * argv [])
{
Flyweightfactory F;
Flyweight * fhello = f. getflyweight ("hello ");
Fhello-> operation (string ("% "));
Flyweight * fworld = f. getflyweight ("world ");
Fworld-> operation (string ("######"));
Flyweight * P = f. getflyweight ("hello ");
P-> operation (string ("@@@@@@"));
Return 0;
}