Home | History | Annotate | Download | only in base
      1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
      2 // Use of this source code is governed by a BSD-style license that can be
      3 // found in the LICENSE file.
      4 
      5 #ifndef BASE_SCOPED_OBSERVER_H_
      6 #define BASE_SCOPED_OBSERVER_H_
      7 
      8 #include <stddef.h>
      9 
     10 #include <algorithm>
     11 #include <vector>
     12 
     13 #include "base/logging.h"
     14 #include "base/macros.h"
     15 
     16 // ScopedObserver is used to keep track of the set of sources an object has
     17 // attached itself to as an observer. When ScopedObserver is destroyed it
     18 // removes the object as an observer from all sources it has been added to.
     19 template <class Source, class Observer>
     20 class ScopedObserver {
     21  public:
     22   explicit ScopedObserver(Observer* observer) : observer_(observer) {}
     23 
     24   ~ScopedObserver() {
     25     RemoveAll();
     26   }
     27 
     28   // Adds the object passed to the constructor as an observer on |source|.
     29   void Add(Source* source) {
     30     sources_.push_back(source);
     31     source->AddObserver(observer_);
     32   }
     33 
     34   // Remove the object passed to the constructor as an observer from |source|.
     35   void Remove(Source* source) {
     36     auto it = std::find(sources_.begin(), sources_.end(), source);
     37     DCHECK(it != sources_.end());
     38     sources_.erase(it);
     39     source->RemoveObserver(observer_);
     40   }
     41 
     42   void RemoveAll() {
     43     for (size_t i = 0; i < sources_.size(); ++i)
     44       sources_[i]->RemoveObserver(observer_);
     45     sources_.clear();
     46   }
     47 
     48   bool IsObserving(Source* source) const {
     49     return ContainsValue(sources_, source);
     50   }
     51 
     52   bool IsObservingSources() const { return !sources_.empty(); }
     53 
     54  private:
     55   Observer* observer_;
     56 
     57   std::vector<Source*> sources_;
     58 
     59   DISALLOW_COPY_AND_ASSIGN(ScopedObserver);
     60 };
     61 
     62 #endif  // BASE_SCOPED_OBSERVER_H_
     63