javascript,php,ruby观察者模式

//被观察者
function Subject() {
    var _this = this;
    this.observers = [];
    this.addObserver = function(obj) {
        _this.observers.push(obj);
    }
    this.deleteObserver = function(obj) {
        var length = _this.observers.length;
        for(var i = 0; i < length; i++) {
            if(_this.observers[i] === obj) {
                _this.observers.splice(i, 1);
            }
        }
    }
    this.notifyObservers = function() {
        var length = _this.observers.length;
        console.log(length)
        for(var i = 0; i < length; i++) {
            _this.observers[i].update();
        }
    }
}
//观察者
function Observer() {
    this.update = function() {
        alert(1)
    }
}
//被观察者
class Subject
{
    private $_observers;
    public function __construct() {
        $this->_observers = array();
    }
    public function add_observer($obs) {
        $this->_observers[] = $obs;
    }
    public funtion delete_observer($bos) {
        $index = array_search($bos, $this->_observers);
        unset($this->_observers[$index]);
    }
    public function notify_observers() {
        foreach($this->_observers as $v) {
            $v->update();
        }
    }
}
//观察者
class Observer
{
    public function __construct() {
        do sth;
    }
    public function update() {
        do sth;
    }
}
require "observer"
#被观察者
class Subject
    include Observable
    def notify
        #do sth
        changed #更新标志为真
        notify_observers(*args) #如果更新标志为真,调用观察者带参数args的方法
    end
end
#观察者
class Obs
    #回调函数,好像只能这么叫
    def update
        #do sth
    end
end

原文地址

Categories: 前端开发