blob: 3754ed57e1d27c3b98f59b8c41262c7d80de9507 [file] [log] [blame]
erg@chromium.org7827c532012-06-23 06:47:30 +09001// 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_
erg@chromium.org7827c532012-06-23 06:47:30 +09007
8#include <algorithm>
9#include <vector>
10
11#include "base/basictypes.h"
12
13// ScopedObserver is used to keep track of the set of sources an object has
14// attached itself to as an observer. When ScopedObserver is destroyed it
15// removes the object as an observer from all sources it has been added to.
16template <class Source, class Observer>
17class ScopedObserver {
18 public:
19 explicit ScopedObserver(Observer* observer) : observer_(observer) {}
20
21 ~ScopedObserver() {
thestig@chromium.orgc6baf062014-04-08 13:01:06 +090022 RemoveAll();
erg@chromium.org7827c532012-06-23 06:47:30 +090023 }
24
25 // Adds the object passed to the constructor as an observer on |source|.
26 void Add(Source* source) {
27 sources_.push_back(source);
28 source->AddObserver(observer_);
29 }
30
jam@chromium.org7bf65a72012-10-06 01:01:57 +090031 // Remove the object passed to the constructor as an observer from |source|.
erg@chromium.org7827c532012-06-23 06:47:30 +090032 void Remove(Source* source) {
33 sources_.erase(std::find(sources_.begin(), sources_.end(), source));
34 source->RemoveObserver(observer_);
35 }
36
thestig@chromium.orgc6baf062014-04-08 13:01:06 +090037 void RemoveAll() {
38 for (size_t i = 0; i < sources_.size(); ++i)
39 sources_[i]->RemoveObserver(observer_);
40 sources_.clear();
41 }
42
jam@chromium.org7bf65a72012-10-06 01:01:57 +090043 bool IsObserving(Source* source) const {
thestig@chromium.orgc6baf062014-04-08 13:01:06 +090044 return std::find(sources_.begin(), sources_.end(), source) !=
45 sources_.end();
jam@chromium.org7bf65a72012-10-06 01:01:57 +090046 }
47
erg@chromium.org7827c532012-06-23 06:47:30 +090048 private:
49 Observer* observer_;
50
51 std::vector<Source*> sources_;
52
53 DISALLOW_COPY_AND_ASSIGN(ScopedObserver);
54};
55
56#endif // BASE_SCOPED_OBSERVER_H_