码迷,mamicode.com
首页 > 其他好文 > 详细

chromium中的观察者模式解析

时间:2018-10-26 00:44:36      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:耦合   server   sign   idg   chromium   github   prot   cas   lamp   

1.观察者模式

  观察者模式(有时又被称为模型-视图(View)模式、源-收听者(Listener)模式或从属者模式)是软件设计模式的一种。在此种模式中,一个目标物件管理所有相依于它的观察者物件,并且在它本身的状态改变时主动发出通知。这通常透过呼叫各观察者所提供的方法来实现。此种模式通常被用来实现事件处理系统。  
  观察者模式(Observer)完美的将观察者和被观察的对象分离开。举个例子,用户界面可以作为一个观察者,业务数据是被观察者,用户界面观察业务数据的变化,发现数据变化后,就显示在界面上。面向对象设计的一个原则是:系统中的每个类将重点放在某一个功能上,而不是其他方面。一个对象只做一件事情,并且将他做好。观察者模式在模块之间划定了清晰的界限,提高了应用程序的可维护性和重用性。观察者设计模式定义了对象间的一种一对多的组合关系,以便一个对象的状态发生变化时,所有依赖于它的对象都得到通知并自动刷新。
2.观察者模式的结构(以chromeium为例)
  Chromium是一个由Google主导开发的网页浏览器,以BSD许可证等多重自由版权发行并开放源代码。下面以观察者模式进行分析:
①抽象观察者接口
 class Observer {
     public:
     virtual void OnFoo(MyWidget* w) = 0;
     virtual void OnBar(MyWidget* w, int x, int y) = 0;
     };

②抽象主题类

void AddObserver(Observer* obs) {
       observer_list_.AddObserver(obs);
     }

void RemoveObserver(Observer* obs) {
       observer_list_.RemoveObserver(obs);
     }

void NotifyFoo() {
       for (auto& observer : observer_list_)
         observer.OnFoo(this);
     }

void NotifyBar(int x, int y) {
      for (FooList::iterator i = observer_list.begin(),
           e = observer_list.end(); i != e; ++i)
        i->OnBar(this, x, y);
     }

private:
     base::ObserverList<Observer> observer_list_;
   };

③具体实现

namespace base {

template <typename ObserverType>
class ObserverListThreadSafe;

template <class ObserverType>
class ObserverListBase
    : public SupportsWeakPtr<ObserverListBase<ObserverType>> {
 public:
  // Enumeration of which observers are notified.
  enum NotificationType {
    // Specifies that any observers added during notification are notified.
    // This is the default type if non type is provided to the constructor.
    NOTIFY_ALL,

    // Specifies that observers added while sending out notification are not
    // notified.
    NOTIFY_EXISTING_ONLY
  };

  // An iterator class that can be used to access the list of observers.
  template <class ContainerType>
  class Iter {
   public:
    Iter();
    explicit Iter(ContainerType* list);
    ~Iter();

    // A workaround for C2244. MSVC requires fully qualified type name for
    // return type on a function definition to match a function declaration.
    using ThisType =
        typename ObserverListBase<ObserverType>::template Iter<ContainerType>;

    bool operator==(const Iter& other) const;
    bool operator!=(const Iter& other) const;
    ThisType& operator++();
    ObserverType* operator->() const;
    ObserverType& operator*() const;

   private:
    FRIEND_TEST_ALL_PREFIXES(ObserverListTest, BasicStdIterator);
    FRIEND_TEST_ALL_PREFIXES(ObserverListTest, StdIteratorRemoveFront);

    ObserverType* GetCurrent() const;
    void EnsureValidIndex();

    size_t clamped_max_index() const {
      return std::min(max_index_, list_->observers_.size());
    }

    bool is_end() const { return !list_ || index_ == clamped_max_index(); }

    WeakPtr<ObserverListBase<ObserverType>> list_;
    // When initially constructed and each time the iterator is incremented,
    // |index_| is guaranteed to point to a non-null index if the iterator
    // has not reached the end of the ObserverList.
    size_t index_;
    size_t max_index_;
  };

  using Iterator = Iter<ObserverListBase<ObserverType>>;

  using iterator = Iter<ObserverListBase<ObserverType>>;
  iterator begin() {
    // An optimization: do not involve weak pointers for empty list.
    // Note: can‘t use ?: operator here due to some MSVC bug (unit tests fail)
    if (observers_.empty())
      return iterator();
    return iterator(this);
  }
  iterator end() { return iterator(); }

  using const_iterator = Iter<const ObserverListBase<ObserverType>>;
  const_iterator begin() const {
    if (observers_.empty())
      return const_iterator();
    return const_iterator(this);
  }
  const_iterator end() const { return const_iterator(); }

  ObserverListBase() : notify_depth_(0), type_(NOTIFY_ALL) {}
  explicit ObserverListBase(NotificationType type)
      : notify_depth_(0), type_(type) {}

  // Add an observer to the list.  An observer should not be added to
  // the same list more than once.
  void AddObserver(ObserverType* obs);

  // Remove an observer from the list if it is in the list.
  void RemoveObserver(ObserverType* obs);

  // Determine whether a particular observer is in the list.
  bool HasObserver(const ObserverType* observer) const;

  void Clear();

 protected:
  size_t size() const { return observers_.size(); }

  void Compact();

 private:
  friend class ObserverListThreadSafe<ObserverType>;

  typedef std::vector<ObserverType*> ListType;

  ListType observers_;
  int notify_depth_;
  NotificationType type_;

  template <class ContainerType>
  friend class Iter;

  DISALLOW_COPY_AND_ASSIGN(ObserverListBase);
};

template <class ObserverType>
template <class ContainerType>
ObserverListBase<ObserverType>::Iter<ContainerType>::Iter()
    : index_(0), max_index_(0) {}

template <class ObserverType>
template <class ContainerType>
ObserverListBase<ObserverType>::Iter<ContainerType>::Iter(ContainerType* list)
    : list_(const_cast<ObserverListBase<ObserverType>*>(list)->AsWeakPtr()),
      index_(0),
      max_index_(list->type_ == NOTIFY_ALL ? std::numeric_limits<size_t>::max()
                                           : list->observers_.size()) {
  EnsureValidIndex();
  DCHECK(list_);
  ++list_->notify_depth_;
}

template <class ObserverType>
template <class ContainerType>
ObserverListBase<ObserverType>::Iter<ContainerType>::~Iter() {
  if (list_ && --list_->notify_depth_ == 0)
    list_->Compact();
}

template <class ObserverType>
template <class ContainerType>
bool ObserverListBase<ObserverType>::Iter<ContainerType>::operator==(
    const Iter& other) const {
  if (is_end() && other.is_end())
    return true;
  return list_.get() == other.list_.get() && index_ == other.index_;
}

template <class ObserverType>
template <class ContainerType>
bool ObserverListBase<ObserverType>::Iter<ContainerType>::operator!=(
    const Iter& other) const {
  return !operator==(other);
}

template <class ObserverType>
template <class ContainerType>
typename ObserverListBase<ObserverType>::template Iter<ContainerType>&
    ObserverListBase<ObserverType>::Iter<ContainerType>::operator++() {
  if (list_) {
    ++index_;
    EnsureValidIndex();
  }
  return *this;
}

template <class ObserverType>
template <class ContainerType>
ObserverType* ObserverListBase<ObserverType>::Iter<ContainerType>::operator->()
    const {
  ObserverType* current = GetCurrent();
  DCHECK(current);
  return current;
}

template <class ObserverType>
template <class ContainerType>
ObserverType& ObserverListBase<ObserverType>::Iter<ContainerType>::operator*()
    const {
  ObserverType* current = GetCurrent();
  DCHECK(current);
  return *current;
}

template <class ObserverType>
template <class ContainerType>
ObserverType* ObserverListBase<ObserverType>::Iter<ContainerType>::GetCurrent()
    const {
  if (!list_)
    return nullptr;
  return index_ < clamped_max_index() ? list_->observers_[index_] : nullptr;
}

template <class ObserverType>
template <class ContainerType>
void ObserverListBase<ObserverType>::Iter<ContainerType>::EnsureValidIndex() {
  if (!list_)
    return;

  size_t max_index = clamped_max_index();
  while (index_ < max_index && !list_->observers_[index_])
    ++index_;
}

template <class ObserverType>
void ObserverListBase<ObserverType>::AddObserver(ObserverType* obs) {
  DCHECK(obs);
  if (ContainsValue(observers_, obs)) {
    NOTREACHED() << "Observers can only be added once!";
    return;
  }
  observers_.push_back(obs);
}

template <class ObserverType>
void ObserverListBase<ObserverType>::RemoveObserver(ObserverType* obs) {
  DCHECK(obs);
  typename ListType::iterator it =
    std::find(observers_.begin(), observers_.end(), obs);
  if (it != observers_.end()) {
    if (notify_depth_) {
      *it = nullptr;
    } else {
      observers_.erase(it);
    }
  }
}

template <class ObserverType>
bool ObserverListBase<ObserverType>::HasObserver(
    const ObserverType* observer) const {
  for (size_t i = 0; i < observers_.size(); ++i) {
    if (observers_[i] == observer)
      return true;
  }
  return false;
}

template <class ObserverType>
void ObserverListBase<ObserverType>::Clear() {
  if (notify_depth_) {
    for (typename ListType::iterator it = observers_.begin();
      it != observers_.end(); ++it) {
      *it = nullptr;
    }
  } else {
    observers_.clear();
  }
}

template <class ObserverType>
void ObserverListBase<ObserverType>::Compact() {
  observers_.erase(std::remove(observers_.begin(), observers_.end(), nullptr),
                   observers_.end());
}

template <class ObserverType, bool check_empty = false>
class ObserverList : public ObserverListBase<ObserverType> {
 public:
  typedef typename ObserverListBase<ObserverType>::NotificationType
      NotificationType;

  ObserverList() {}
  explicit ObserverList(NotificationType type)
      : ObserverListBase<ObserverType>(type) {}

  ~ObserverList() {
    // When check_empty is true, assert that the list is empty on destruction.
    if (check_empty) {
      ObserverListBase<ObserverType>::Compact();
      DCHECK_EQ(ObserverListBase<ObserverType>::size(), 0U);
    }
  }

  bool might_have_observers() const {
    return ObserverListBase<ObserverType>::size() != 0;
  }
};

}  // namespace base

3.观察者模式的实现

技术分享图片

 

4.应用观察者模式的优缺点

  观察者模式的优点:观察者模式在被观察者和观察者之间建立一个抽象的耦合。被观察者角色所知道的只是一个具体观察者列表,每一个具体观察者都符合一个抽象观察者的接口。被观察者并不认识任何一个具体观察者,它只知道它们都有一个共同的接口。由于被观察者和观察者没有紧密地耦合在一起,因此它们可以属于不同的抽象化层次。如果被观察者和观察者都被扔到一起,那么这个对象必然跨越抽象化和具体化层次。同时观察者模式支持广播通讯。被观察者会向所有的登记过的观察者发出通知。

  观察者模式的缺点:如果一个被观察者对象有很多的直接和间接的观察者的话,将所有的观察者都通知到会花费很多时间。如果在被观察者之间有循环依赖的话,被观察者会触发它们之间进行循环调用,导致系统崩溃。在使用观察者模式是要特别注意这一点。如果对观察者的通知是通过另外的线程进行异步投递的话,系统必须保证投递是以自恰的方式进行的。虽然观察者模式可以随时使观察者知道所观察的对象发生了变化,但是观察者模式没有相应的机制使观察者知道所观察的对象是怎么发生变化的。(借鉴于http://www.bianchengzhe.com)

chromeium项目链接:https://github.com/zengcan/libchrome

chromeium观察者模式实现连接:https://github.com/zengcan/libchrome/blob/master/observer_list.h

 

chromium中的观察者模式解析

标签:耦合   server   sign   idg   chromium   github   prot   cas   lamp   

原文地址:https://www.cnblogs.com/lcy1996/p/9853688.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!