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.
5 #ifndef BASE_SCOPED_OBSERVER_H_
6 #define BASE_SCOPED_OBSERVER_H_
11 #include "base/basictypes.h"
12 #include "base/logging.h"
14 // ScopedObserver is used to keep track of the set of sources an object has
15 // attached itself to as an observer. When ScopedObserver is destroyed it
16 // removes the object as an observer from all sources it has been added to.
17 template <class Source
, class Observer
>
18 class ScopedObserver
{
20 explicit ScopedObserver(Observer
* observer
) : observer_(observer
) {}
26 // Adds the object passed to the constructor as an observer on |source|.
27 void Add(Source
* source
) {
28 sources_
.push_back(source
);
29 source
->AddObserver(observer_
);
32 // Remove the object passed to the constructor as an observer from |source|.
33 void Remove(Source
* source
) {
34 auto it
= std::find(sources_
.begin(), sources_
.end(), source
);
35 DCHECK(it
!= sources_
.end());
37 source
->RemoveObserver(observer_
);
41 for (size_t i
= 0; i
< sources_
.size(); ++i
)
42 sources_
[i
]->RemoveObserver(observer_
);
46 bool IsObserving(Source
* source
) const {
47 return std::find(sources_
.begin(), sources_
.end(), source
) !=
54 std::vector
<Source
*> sources_
;
56 DISALLOW_COPY_AND_ASSIGN(ScopedObserver
);
59 #endif // BASE_SCOPED_OBSERVER_H_