jack06215

[tutorial] Flyweight pattern

Jul 17th, 2020 (edited)
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.13 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. class Gazillion
  6. {
  7.   public:
  8.     Gazillion(int value_one)
  9.     {
  10.         m_value_one = value_one;
  11.         cout << "ctor: " << m_value_one << '\n';
  12.     }
  13.     ~Gazillion()
  14.     {
  15.         cout << m_value_one << ' ';
  16.     }
  17.     void report(int value_two)
  18.     {
  19.         cout << m_value_one << value_two << ' ';
  20.     }
  21.   private:
  22.     int m_value_one;
  23. };
  24.  
  25. class Factory
  26. {
  27.   public:
  28.     static Gazillion *get_fly(int in)
  29.     {
  30.         if (!s_pool[in])
  31.           s_pool[in] = new Gazillion(in);
  32.         return s_pool[in];
  33.     }
  34.     static void clean_up()
  35.     {
  36.         cout << "dtors: ";
  37.         for (int i = 0; i < X; ++i)
  38.           if (s_pool[i])
  39.             delete s_pool[i];
  40.         cout << '\n';
  41.     }
  42.     static int X, Y;
  43.   private:
  44.     static Gazillion *s_pool[];
  45. };
  46.  
  47. int Factory::X = 100, Factory::Y = 100;
  48. Gazillion *Factory::s_pool[] =
  49. {
  50.   0, 0, 0, 0, 0, 0
  51. };
  52.  
  53. int main()
  54. {
  55.   for (int i = 0; i < Factory::X; ++i)
  56.   {
  57.     for (int j = 0; j < Factory::Y; ++j)
  58.       Factory::get_fly(i)->report(j);
  59.     cout << '\n';
  60.   }
  61.   Factory::clean_up();
  62.  
  63.   return 0;
  64. }
Add Comment
Please, Sign In to add comment