3_observer

#Observer

成就系统
achievements system
玩家完成某种成就后,通知监督者,监督者做出相应出来


```
//简单来说就是事件触发的时候, 通知监督者

class Observer
{
public:
  virtual ~Observer() {}
  virtual void onNotify(const Entity& entity, Event event) = 0;
};

class Achievements : public Observer
{
public:
  virtual void onNotify(const Entity& entity, Event event)
  {
    switch (event)
    {
    case EVENT_ENTITY_FELL:
      if (entity.isHero() && heroIsOnBridge_)
      {
        unlock(ACHIEVEMENT_FELL_OFF_BRIDGE);
      }
      break;

      // Handle other events, and update heroIsOnBridge_...
    }
  }

private:
  void unlock(Achievement achievement)
  {
    // Unlock if not already unlocked...
  }

  bool heroIsOnBridge_;
};

class Subject
{
private:
  Observer* observers_[MAX_OBSERVERS];
  int numObservers_;
  
 public:
  void addObserver(Observer* observer)
  {
    // Add to array...
  }

  void removeObserver(Observer* observer)
  {
    // Remove from array...
  }

  
  protected:
  void notify(const Entity& entity, Event event)
  {
    for (int i = 0; i < numObservers_; i++)
    {
      observers_[i]->onNotify(entity, event);
    }
  }
  
  
};
```

语言绑定:
    
    java mvc
    c# event


其他例子:

```
1 ui得到数据改变的通知
2 数据改变,ui即时表现出来
```

 

posted @ 2015-01-16 16:54  summernight  阅读(106)  评论(0编辑  收藏  举报