blob: 60aee19e3c3b7407bd19fe4f6f154450fc1f7677 [file] [log] [blame]
[email protected]5924a0b2012-04-27 17:02:281// 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 ASH_WM_SCOPED_OBSERVER_H_
6#define ASH_WM_SCOPED_OBSERVER_H_
7#pragma once
8
9#include <algorithm>
10#include <vector>
11
12#include "base/basictypes.h"
13
14namespace ash {
15namespace internal {
16
17// ScopedObserver is used to keep track of the set of sources an object has
18// attached itself to as an observer. When ScopedObserver is destroyed it
19// removes the object as an observer from all sources it has been added to.
20template <class Source, class Observer>
21class ScopedObserver {
22 public:
23 explicit ScopedObserver(Observer* observer) : observer_(observer) {}
24
25 ~ScopedObserver() {
26 for (size_t i = 0; i < sources_.size(); ++i)
27 sources_[i]->RemoveObserver(observer_);
28 }
29
30 // Adds the object passed to the constructor as an observer on |source|.
31 void Add(Source* source) {
32 sources_.push_back(source);
33 source->AddObserver(observer_);
34 }
35
36 // Removse the object passed to the constructor as an observer from |source|.
37 void Remove(Source* source) {
38 sources_.erase(std::find(sources_.begin(), sources_.end(), source));
39 source->RemoveObserver(observer_);
40 }
41
42 private:
43 Observer* observer_;
44
45 std::vector<Source*> sources_;
46
47 DISALLOW_COPY_AND_ASSIGN(ScopedObserver);
48};
49
50} // namespace internal
51} // namespace ash
52
53#endif // ASH_WM_SCOPED_OBSERVER_H_