Advertisement
Guest User

Untitled

a guest
May 22nd, 2018
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.20 KB | None | 0 0
  1. class RealImage
  2. {
  3.     int m_id;
  4.   public:
  5.     RealImage(int i)
  6.     {
  7.         m_id = i;
  8.         cout << "   $$ ctor: " << m_id << '\n';
  9.     }
  10.     ~RealImage()
  11.     {
  12.         cout << "   dtor: " << m_id << '\n';
  13.     }
  14.     void draw()
  15.     {
  16.         cout << "   drawing image " << m_id << '\n';
  17.     }
  18. };
  19.  
  20. // 1. Design an "extra level of indirection" wrapper class
  21. class Image
  22. {
  23.     // 2. The wrapper class holds a pointer to the real class
  24.     RealImage *m_the_real_thing;
  25.     int m_id;
  26.     static int s_next;
  27.   public:
  28.     Image()
  29.     {
  30.         m_id = s_next++;
  31.         // 3. Initialized to null
  32.         m_the_real_thing = 0;
  33.     }
  34.     ~Image()
  35.     {
  36.         delete m_the_real_thing;
  37.     }
  38.     void draw()
  39.     {
  40.         // 4. When a request comes in, the real object is
  41.         //    created "on first use"
  42.         if (!m_the_real_thing)
  43.           m_the_real_thing = new RealImage(m_id);
  44.         // 5. The request is always delegated
  45.         m_the_real_thing->draw();
  46.     }
  47. };
  48. int Image::s_next = 1;
  49.  
  50. int main()
  51. {
  52.   Image images[5];
  53.  
  54.   for (int i; true;)
  55.   {
  56.     cout << "Exit[0], Image[1-5]: ";
  57.     cin >> i;
  58.     if (i == 0)
  59.       break;
  60.     images[i - 1].draw();
  61.   }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement