// Purpose. Flyweight
//
// Discussion. Trying to use objects const int X = 6;
// at very low levels of granularity const int Y = 10;
// is nice, but the overhead may be
// prohibitive. Flyweight suggests class Gazillion {
// removing the non-shareable state public:
// from the class, and having the cli- Gazillion( int in ) {
// ent supply it when methods are val1_ = in;
// called. This places more respon- cout << "ctor: "<< val1_<<endl; }
// sibility on the client, but, con- ~Gazillion() {
// siderably fewer instances of the cout << val1_ << ' '; }
// Flyweight class are now created. void report( int in ) {
// Sharing of these instances is fa- cout << val1_ << in << ' '; }
// cilitated by introducing a Factory private:
// class that maintains a "cache" of int val1_;
// existing Flyweights. };
//
// In this example, the "X" state is class Factory {
// considered shareable (within each public:
// row anyways), and the "Y" state has static Gazillion* getFly(int in) {
// been externalized (it is supplied if ( ! pool_[in])
// by the client when report() is pool_[in] =
// called). new Gazillion( in );
return pool_[in];
static void cleanUp() {
const int X = 6; cout << "dtors: ";
const int Y = 10; for (int i=0; i < X; i++)
if (pool_[i])
class Gazillion { delete pool_[i];
public: cout << endl;
Gazillion() { }
val1_ = num_ / Y; private:
val2_ = num_ % Y; static Gazillion* pool_[X];
num_++; };
}
void report() { Gazillion* Factory::pool_[] = {
cout << val1_ << val2_ << ' '; 0,0,0,0,0,0 };
}
private: void main( void )
int val1_; {
int val2_; for (int i=0; i < X; i++)
static int num_; {
}; for (int j=0; j < Y; j++)
Factory::getFly(i)->report(j);
int Gazillion::num_ = 0; cout << endl;
}
void main( void ) Factory::cleanUp();
{ }
Gazillion matrix[X][Y];
for (int i=0; i < X; i++) // ctor: 0
{ // 00 01 02 03 04 05 06 07 08 09
for (int j=0; j < Y; j++) // ctor: 1
matrix[i][j].report(); // 10 11 12 13 14 15 16 17 18 19
cout << endl; // ctor: 2
} // 20 21 22 23 24 25 26 27 28 29
} // ctor: 3
// 30 31 32 33 34 35 36 37 38 39
// 00 01 02 03 04 05 06 07 08 09 // ctor: 4
// 10 11 12 13 14 15 16 17 18 19 // 40 41 42 43 44 45 46 47 48 49
// 20 21 22 23 24 25 26 27 28 29 // ctor: 5
// 30 31 32 33 34 35 36 37 38 39 // 50 51 52 53 54 55 56 57 58 59
// 40 41 42 43 44 45 46 47 48 49 // dtors: 0 1 2 3 4 5
// 50 51 52 53 54 55 56 57 58 59