Intent:
Use sharing technology to effectively support a large number of fine-grained objects
Applicable:
An application uses a large number of objects.
A large amount of storage overhead is caused by the use of a large number of objects.
Most States of objects can be changed to external states.
If you delete the external state of an object, you can replace multiple groups of objects with fewer shared objects.
UML
Resolution:
The flywweight mode is widely used when shared objects are frequently used.
// 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;
// Check whether any object exists in the list
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. getflyweight ("hello ");
Flyweightfactory. getflyweight ("world ");
Flyweightfactory. getflyweight ("hello ");
System ("pause ");
Return 0;
}