Bomb Pattern

Bomb

  • called a “mini pattern”

  • problem: want event to execute when a block exits

  • solution: define class with code to be executed in destructor; declare instance of class at top of block

  • examples:

    • check postconditions for method

    • set cursor to hourglass and restore when exit function (from BCB help notes):

      // in .h file:
      
      enum MouseCursor;
      
      // from Borland C++ Builder help notes
      class WaitCursor {
      public:
          WaitCursor();
         ~WaitCursor();
      private:
          MouseCursor saved_cursor;
      };
      
      // in .cpp file:
      
      WaitCursor::WaitCursor()
      {
          saved_cursor = Screen->Cursor;
          Screen->Cursor = crHourGlass;
      }
      
      WaitCursor::~WaitCursor()
      {
          Screen->Cursor = saved_cursor;
      }
      
    • Usage:

      void read_database()
      {
         WaitCursor just_a_second;
         ... code to open database, read items, close connection
      }
      
  • Relies on C++ “destructors” - cannot do this in Java