观察者模式的实现 [英] Observer pattern implementation

查看:91
本文介绍了观察者模式的实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难确切地了解什么是观察者模式,但是我为我的项目编写了以下代码.它使用SDL.我正在使用boost库来实现信号,因此实现了我的观察者模式.这看起来正确吗?

I had a hard time understand exactly what an observer pattern was, but I produced the following code for my project. It uses SDL. I am using the boost library to implement signals and therefore implementing my observer pattern. Does this look correct?

/* This is setting up our signal for sending observations */
boost::signals2::signal<void (char, int, int)> sig;

/* Subjects the Observer will connect with */
sig.connect(&setChest);
sig.connect(&setNonTraverse);
sig.connect(&setEntry);
sig.connect(&setExit);

std::cout << "Waiting for user-interaction. Press on the 'X' to quit" << std::endl;

while ( !quit ) {               
    status = SDL_WaitEvent(&event);   //wait for an event to occur
    switch (event.type) {           //check the event type
        case SDL_KEYDOWN:           //Check if a key was pressed.     
        key = SDL_GetKeyName(event.key.keysym.sym);
        break;
        case SDL_MOUSEBUTTONUP:
        sig(key[0],event.button.x/32,event.button.y/32);
        break;
        case SDL_QUIT:          // Click on the 'X' to close the window.
        exit ( 1 );
        break;
    }
  } //while
  return true;
}

推荐答案

您发布的代码是观察者的代码.

Your posted code is that of the Observer.

在观察者"模式中,观察者不会直接对主体的状态变化做出反应.相反,主题通过调用观察者的回调将任何更改通知观察者.这就是观察者必须向主题注册的原因,而不仅仅是轮询(检查while循环中的状态)主题.

In the Observer pattern, the observer doesn't react directly to the subjects' state changes. Instead, the subject informs the observer of any changes by invoking the observer's callback. This is why the observer must register with the subject, instead of merely polling (checking the state in a while loop) the subject.

我不太熟悉C ++,但是下面是一些类似Java的伪代码,概述了基本思想:

I'm not too familiar with C++, but here is some Java-like pseudocode that outlines the basic idea:

class Observer{
    public Observer(Subject subject){
        subject.register(this);
    }
    public void updateFromSubject(Subject subject){
        //respond to change
    }
}

class Subject{
    List<Observer> observers;
    public void register(Observer observer){
        observers.add(observer);
    }
    private void notifyObservers(){
        for(Observer obs : observers){
            obs.updateFromSubject(this);
        }
    }
    public void changeStateToNewState(Object o){
        .... //business logic
        notifyObservers();
}

请注意缺少while循环,这意味着观察者只是在实际事件发生之前才做任何工作,而不是每秒检查一百万次标志以查看其是否改变.

Notice the lack of a while loop, which means that the observer simply doesn't do any work until an actual event occurs, instead of checking a flag a million times a second just to see if it changed.

这篇关于观察者模式的实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆